Home > Mobile >  PHP: Insert Data using AJAX
PHP: Insert Data using AJAX

Time:03-12

I'm new in AJAX and I'm currently working with a QR scanner. I'm having a problem with inserting a data on the MySQL database. I tried searching for hours on how can I insert a data using AJAX but nothing seems to be working. This is the last step that I need to do for the system to work. Can somebody help me with this? Thank you in advance!

Here's the scenario:

  1. Scan the QR code
  2. Search the QR code in the users table
  3. The User ID will be inserted in the logs table
function onScanSuccess(qrCodeMessage) {
    if (qrCodeMessage !== lastResult) {
          countResults;
        lastResult = qrCodeMessage;

        $.ajax({
          url:'db_scan.php',
          method:'POST',
          data:{pcode:qrCodeMessage},
          error:err=>{
            console.log(err)
            alert_toast('An Error Occured.');
          },
          success:function(resp){
            console.log('Success?');
            if(resp == 1){
              console.log('Resp=1');
               swal({
                  title: 'Welcome',
                  text: 'Enjoy your visit...',
                  icon: 'success',
                  timer: 2000,
                  buttons: false,
              })
            }else if(resp ==3){
              console.log('Resp=3');
              swal({
                  title: 'Code is not Valid',
                  text: 'Scan a register QR Code',
                  icon: 'error',
                  timer: 2000,
                  buttons: false,
              })
            }else{
            alert_toast('An Error Occured.');
            }

          }
        })
    }
}

        var html5QrcodeScanner = new Html5QrcodeScanner(
            "qr-reader", { fps: 10, qrbox: 250 });
        html5QrcodeScanner.render(onScanSuccess);

db_scan.php

  $pcode=$_POST['pcode'];
  $u_id = "SELECT * FROM `users` WHERE qr='$pcode'";
  $sql = "INSERT INTO logs set u_id = '$u_id";

  $result = $conn->query($sql);

  if ($result == TRUE) {
      echo "Record has been added!";
  } else {
      echo "Error:" . $sql . "<br>" . $conn->error;
  }

Reference: HTML5 QR Reader

SOLUTION: I used the solution that were given by Harvi Dent and it seems that I forgot to put <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> on my code that's why it not really working.

CodePudding user response:

Your query is too vulnerable to sql injection, never use mysqli and non parameterized queries.

Instead, use parametrized pdo queries to work with the base

Your php code should look something like this

    // change for connect to db
    $pdo = new PDO('mysql:host=' . DB_HOSTNAME . ';dbname=' . DB_DATABASE, DB_USERNAME, DB_PASSWORD); 
    
    $pcode = $_POST['pcode'];
    
    // start.  get id from db
    $u_id_sql = "SELECT * FROM `users` WHERE qr=:qr";
    $stmt = $pdo->prepare($u_id_sql);
    $stmt->execute(['qr' => $pcode]);
    $user_row = $stmt->fetch(PDO::FETCH_ASSOC); // her array with id
    // end.  get id from db
    
    // start insert
    $sql = "INSERT INTO `logs` set u_id = :user_qr_id";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['user_qr_id' => $user_row['id']]);
    $stmt->fetch();
    // end insert
  • Related