0

I am working on a scanner reader, so I used ajax when the code is read by the scanner, it should insert data to the database. The problem is the data is not inserting.

Inside the script / Ajax - query is the variable I used to get the data (name)

  var query = $('#scanned-QR').val();
     fetch_customer_data(query);


      $(document).on('keyup', '#scanned-QR', function(){
       var query = $(this).val();
       fetch_customer_data(query);
      });

      function fetch_customer_data(query = '') 
      {

         $.ajax({
           url:"validScan.php",
           method: 'GET',
           data:{query:query},
           dataType: 'json',
           success:function(data) {
           console.log(data);
              if (data.status == '1') {

                decoder.stop();
                alert('Sucess!');

              }
              else if(data.status=='0'){

                 decoder.stop();
                 alert('Fail!');

              }

             },
               error:function(err){

               console.log(err);
             }
          });
       }

My Input/Textarea

<textarea id="scanned-QR" name="scanQR" readonly></textarea>

MySQL

<?php
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);

  $link = mysqli_connect("localhost","root","");
  mysqli_select_db($link, "schedule");

  $query = $_GET['query'];

  $res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");


  if (mysqli_num_rows($res) > 0) {
        $respose = array('status'=>'1');//1 for success
        echo json_encode($respose );        
  } else {
        $respose = array('status'=>'0');//0 for fail
        echo json_encode($respose );        
  }
  mysqli_close($link);


?>
3
  • Can you post the error message with : echo mysqli_error($link); Also, your attendance table has only two columns? (PK and name), if no, maybe the other columns are "not null" so it raised an error. Commented Jan 31, 2020 at 6:19
  • @piratefache , yea, I do it for purpose, to try it in the simplest way and not adding too much. actually there's no error. the data is not inserting, it DOES however gives data but it is blank data Commented Jan 31, 2020 at 6:25
  • You can print $query to be sure it's not empty. Also in your query you can single quote your column name like that : INSERT INTO attendance (`name`) VALUES ('$query') Commented Jan 31, 2020 at 6:32

3 Answers 3

1

For insert query, result will return as boolean, So mysqli_num_rows($res) won't accept boolean argument. mysqli_num_rows() expects parameter 1 to be mysqli_result

So you can simply check by below, whether it is inserted or not:

if ($res) {
    $respose = array('status'=>'1');//1 for success
    echo json_encode($respose);
    exit;   
} else {
    $respose = array('status'=>'0');//0 for fail
    echo json_encode($respose); 
    exit;   
}
mysqli_close($link);
Sign up to request clarification or add additional context in comments.

Comments

0

You should use exit try following code :

ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);

  $link = mysqli_connect("localhost","root","");
  mysqli_select_db($link, "schedule");

  $query = $_GET['query'];

  $res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");


  if (mysqli_num_rows($res) > 0) {
        $respose = array('status'=>'1');//1 for success
        echo json_encode($respose );
        exit;   
  } else {
        $respose = array('status'=>'0');//0 for fail
        echo json_encode($respose ); 
        exit;   
  }
  mysqli_close($link);
  exit;

3 Comments

tried it but it will not change anything, adding exit is also the other code above.
Adding exit; changes nothing, except it will never reach mysqli_close().
@SummerWinter That means that you changed method: 'GET', to method: 'POST', in your ajax.
0

mysqli_num_rows() is for getting the number of rows returned from a SELECT query. You need to check the number of affected rows instead.

You should also be using a prepared statement, and I also recommend that you set up MySQLi to throw errors. I also prefer the object-oriented approach.

<?php 
// Configure MySQLi to throw exceptions on failure 
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Init connection
$link = new mysqli("localhost", "root", "", "schedule");
$response = [];

// Prepare the statement and execute it
$stmt = $link->prepare("INSERT INTO attendance (name) VALUES (?)");
$stmt->bind_param("s", $_GET['query']);
$stmt->execute();

// Check the number of inserted rows
if ($stmt->affected_rows) {
    $response['status'] = 1;
} else {
    $response['status'] = 0;
}

// Close the statement and connection
$stmt->close();
$link->close();

echo json_encode($response);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.