Insert in MySQL database using PHP PDO Web Service

1

I am developing a PHP Web Service to consult and insert data in a database. Until now, the web service is able to search the table for records, however it is not able to insert them . There are only three php files.

The first one is dbconn.php

<?php

$host         = "localhost";
$username     = "root";
$password     = "";
$dbname       = "iesatickets";

try {
    $dbconn = new PDO('mysql:host=localhost;dbname=iesatickets', $username, $password);
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

?>

The second is the model for the webservice server.

<?php
 require_once('dbconn.php');
 require_once('lib/nusoap.php'); 
 $server = new nusoap_server();

/* Fetch 1 ticket data */
function fetchTicketData($idticket){
    global $dbconn;
    $sql = "select id, title, description, project_id, tecnico_id from ticket where title = :idticket";
  // prepare sql and bind parameters
    $stmt = $dbconn->prepare($sql);
    $stmt->bindParam(':idticket', $idticket);
    // insert a row
    $stmt->execute();
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    return json_encode($data);
    $dbconn = null;
}

/* Insert Ticket data */
function insertTicketData($idticket){
    global $dbconn;
    $sql_insert = "insert into ticket (id, title, description, tecnico_id) values (:idticket, :nombreTicket, :descripcionTicket, :tecnicotick)";
    $stmt = $dbconn->prepare($sql_insert);
    // insert a row
    $stmt->execute();
    $result = $stmt->execute(array(':id'=>$idticket, ':title'=>$nombreTicket, ':description'=>$descripcionTicket, ':tecnico_id'=>$tecnicotick));
    if($result) {
        echo "Your ticket has been posted";

        }
    else {
        echo "Something went wrong. Please try again.";
        }

    $dbconn = null;
}
$server->configureWSDL('ticketServer', 'urn:ticket');
$server->register('fetchTicketData',
            array('idticket' => 'xsd:string'),  //parameter
            array('data' => 'xsd:string'),  //output
            'urn:ticket',   //namespace
            'urn:ticket#fetchTicketData' //soapaction
            );  
$server->service(file_get_contents("php://input"));

?>

And finally the client, where I look and insert.

<?php


      ini_set('display_errors', true);
      error_reporting(E_ALL); 


    require_once('lib/nusoap.php');
    $error  = '';
    $result = array();
    $wsdl = "http://localhost/wstickets/webservice-server.php?wsdl";

    if(isset($_POST['sub'])){
        $idticket = trim($_POST['idticket']);
        if(!$idticket){
            $error = 'idticket cannot be left blank.';
        }

        if(!$error){
            $client = new nusoap_client($wsdl, true);
            $err = $client->getError();
            if ($err) {
                echo '<h2>Constructor error</h2>' . $err;
                exit();
            }
             try {
                $result = $client->call('fetchTicketData', array($idticket));
                $result = json_decode($result);
              }catch (Exception $e) {
                echo 'Caught exception: ',  $e->getMessage(), "\n";
             }
        }
    }

    if(isset($_POST['insert'])){
        $idticket = $_POST['idticket'];
        $nombreTicket = $_POST['nameticket'];
        $descripcionTicket = $_POST['descriptionticket'];
        $tecnicotick = $_POST['tecnicoticket'];
        if(!$idticket){
            $error = 'The ID cannot be left blank.';
        }
        if(!$nombreTicket){
            $error = 'The title cannot be left blank.';
        }
        if(!$descripcionTicket){
            $error = 'The description cannot be left blank.';
        }
        if(!$tecnicotick){
            $error = 'The technicians ID cannot be left blank.';
        }
        if(!$error){
            $client = new nusoap_client($wsdl, true);
            $err = $client->getError();
            if ($err) {
                echo '<h2>Constructor error</h2>' . $err;
                exit();
            }
             try {
                $result = $client->call('insertTicketData', array($idticket));
                $result = json_decode($result);
              }catch (Exception $e) {
                echo 'Caught exception: ',  $e->getMessage(), "\n";
             }
        }
    }

?>

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>IESATickets Web Service</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>

    <div class="container">
      <h2>Webservice para IESATickets</h2>
      <p>Ingrese el <strong>número de ticket</strong> para obtener la información <strong>presionando el botón de</strong> obtener.</p>
      <br />       
      <div class='row'>
        <form class="form-inline" method = 'post' name='form1'>
            <?php if($error) { ?> 
                <div class="alert alert-danger fade in">
                    <a href="#" class="close" data-dismiss="alert">&times;</a>
                    <strong>Error!</strong>&nbsp;<?php echo $error; ?> 
                </div>
            <?php } ?>
            <div class="form-group">
              <label for="email">ID:</label>
              <input type="text" class="form-control" name="idticket" id="idticket" placeholder="Ingrese ID">
            </div>
            <br>
            <div class="form-group">
              <label for="email">Nombre</label>
              <input type="text" class="form-control" name="nameticket" id="nameticket" placeholder="Ingrese ID">
            </div>
            <br>        
            <div class="form-group">
              <label for="email">Descripción</label>
              <input type="text" class="form-control" name="descriptionticket" id="descriptionticket" placeholder="Ingrese ID">
            </div>
            <br>
            <div class="form-group">
              <label for="email">Técnico Asignado</label>
              <input type="text" class="form-control" name="tecnicoticket" id="tecnicoticket" placeholder="Ingrese ID">
            </div>  
            <button type="submit" name='sub' class="btn btn-default">Buscar</button>
            <button type="submit" name='insert' class="btn btn-default">Insertar</button>
        </form>
       </div>
       <br />
       <h2>Información del Ticket</h2>
      <table class="table">
        <thead>
          <tr>
            <th>Título</th>
            <th>Descripción</th>
            <th>Título</th>
            <th>Título</th>
            <th>Título</th>
          </tr>
        </thead>
        <tbody>
        <?php if(count($result)){ 
                for ($i=0; $i < count($result); $i++) { ?>
                  <tr>
                    <td><?php echo $result->id; ?></td>
                    <td><?php echo $result->title; ?></td>
                    <td><?php echo $result->description; ?></td>
                    <td><?php echo $result->project_id; ?></td> 
                    <td><?php echo $result->tecnico_id; ?></td>
                  </tr>
          <?php 
                }
            }else{ ?>
                <tr>
                    <td colspan='5'>Ingrese el ID del ticket y el botón obtener</td>
                  </tr>
            <?php } ?>
        </tbody>
      </table>
    </div>

    </body>
    </html>

Everything in theory should be working well. When I press the search button, it does throw the results correctly, but when I try to insert it, it apparently inserts them, but when checking the database, or with the same webservice, I find that it did not insert anything. What am I doing wrong?

The structure of the ticket table is as follows: id , title , description and tecnico_id .

    
asked by Josue Marin 05.11.2018 в 22:53
source

1 answer

1

Your insertTicketData function has two problems:

  • You are running twice, in one you do not send anything and it is certain that the code will fail in that line
  • In the second execute , which should be correct, the array key names do not match the :nombre markers you used in the prepared query. Those names must be exactly the same and eye, that has nothing to do with the names of the columns or the varaibles, although usually the same column names are used. The important thing here is that use the same markers in the prepared query and in the array .

Fix your function like this:

function insertTicketData($idticket){
    global $dbconn;
    /*
       *Aquí, todos los marcadores que uses con :nombre
       *deben ser los mismos en el array que pasas en el exectue
       *usaré los nombres de columna, para menos confusión
       *Esos marcadores no tienen nada que ver por cómo se llamen las variables
    */
    $sql_insert = "insert into ticket (id, title, description, tecnico_id) values (:id, :title, :description, :tecnico_id)";
    $stmt = $dbconn->prepare($sql_insert);
    // insert a row
    //$stmt->execute();
    $result = $stmt->execute(array(':id'=>$idticket, ':title'=>$nombreTicket, ':description'=>$descripcionTicket, ':tecnico_id'=>$tecnicotick));
    if($result) {
        echo "Your ticket has been posted";

        }
    else {
        echo "Something went wrong. Please try again.";
        }

    $dbconn = null;
}

The quid of the issue is that, if you write a query like this:

insert into 
    ticket (
                id, 
                title, 
                description, 
                tecnico_id
            ) values (
                :id, 
                :title, 
                :description, 
                :tecnico_id
            )

In execute the names you use in the array must match each name tag:

array(
        ':id'=>$idticket, 
        ':title'=>$nombreTicket,
        ':description'=>$descripcionTicket, 
        ':tecnico_id'=>$tecnicotick
    )

Up, in the name marker you can put whatever, for example: :pepe instead of :id , but if you do that, in the array you have to also put :pepe and not :id .

    
answered by 05.11.2018 в 23:08