Php 将mysqli脚本更新为PDO语句

Php 将mysqli脚本更新为PDO语句,php,mysql,pdo,Php,Mysql,Pdo,我是一名新手,我正在PDO领域迈出第一步,我正在尝试将这个脚本从mysqli更新为PDO。该脚本用于通过jQuery从数据库中删除记录 mySql数据库的新连接: $host = "localhost"; $user = "root"; $password = ""; $dbname = "test-2"; try { $con = new PDO("mysql:host={$host};dbname={$dbname}", $user, $password); } // sh

我是一名新手,我正在PDO领域迈出第一步,我正在尝试将这个脚本从mysqli更新为PDO。该脚本用于通过jQuery从数据库中删除记录

mySql数据库的新连接:

$host = "localhost"; 
$user = "root";
$password = ""; 
$dbname = "test-2"; 

try {
    $con = new PDO("mysql:host={$host};dbname={$dbname}", $user, $password);
}

// show error
catch(PDOException $exception){
    echo "Connection error: " . $exception->getMessage();
}
问题与删除脚本有关。这是原始连接(取自本教程:),其中引用了旧连接

include "config.php";

$id = $_POST['id'];

if($id > 0){

  // Check record exists
  $checkRecord = mysqli_query($con,"SELECT * FROM gallery WHERE id_gallery=".$id);
  $totalrows = mysqli_num_rows($checkRecord);

  if($totalrows > 0){
    // Delete record
    $query = "DELETE FROM gallery WHERE id_gallery=".$id;
    mysqli_query($con,$query);
    echo 1;
    exit;
  }
}

echo 0;
exit;
和我要更新的脚本一样。它不起作用,因为它向我发出“无效ID”警报

include "config.php";

$id = $_POST['id'];

if($id > 0){

  // Check record exists
  $checkRecord = "SELECT * FROM gallery WHERE id_gallery=".$id;
  $stmt = $con->prepare($checkRecord);
    $stmt->bindParam(1, $id);
     $stmt->execute();

  $totalrows = $stmt->fetchColumn()

  if($totalrows > 0){
    // Delete record
    $query = "DELETE FROM gallery WHERE id_gallery=".$id;
    $stmt = $con->prepare($query);
    $stmt->bindParam(1, $id);
    $stmt->execute();
    echo 1;
    exit;
  }
}

echo 0;
exit;
script.js

    $(document).ready(function(){

    $('.delete').click(function(){
        var el = this;
        var id = this.id;
        var splitid = id.split("_");

        // Delete id
        var deleteid = splitid[1];

        // AJAX Request
        $.ajax({
            url: 'remove.php',
            type: 'POST',
            data: { id:deleteid },
            success: function(response){

                if(response == 1){
                    // Remove row from HTML Table
                    $(el).closest('tr').css('background','tomato');
                    $(el).closest('tr').fadeOut(800,function(){
                        $(this).remove();
                    });
                }else{
                    alert('Invalid ID.');
                }
            }
        });
    });
});

原始mysqli代码和PDO代码实际上都没有创建任何绑定参数

你有这个:

$checkRecord = "SELECT * FROM gallery WHERE id_gallery=".$id;
$stmt = $con->prepare($checkRecord);
$stmt->bindParam(1, $id);
$stmt->execute();
毫无疑问,当您请求bindParam()时,PDO会感到困惑,因为您没有在SQL查询中放入任何参数占位符。“将参数…绑定到什么??”它正确地提出疑问

您应该使用以下选项:

$checkRecord = "SELECT * FROM gallery WHERE id_gallery=?";
$stmt = $con->prepare($checkRecord);
$stmt->execute([$id]);

更多代码示例可在文档中找到。

第一个问题,我真的需要运行此选择吗?我建议使用下面的代码

    include "config.php";

    $id = $_POST['id'];

    if($id > 0){

      // Delete record
      $checkRecord = "DELETE FROM gallery WHERE id_gallery= :id ";
      $stmt = $con->prepare($checkRecord);
      $stmt->bindParam(":id", $id, PDO::PARAM_INT);      

      // It executes the delete, if any record is deleted, it will print "Registration deleted"
      if($stmt->execute()){
        echo "Registration deleted";
      }else{
        echo "Id does not exist";
      }
    }
exit;
我还建议您始终使用
PDO::PARAM\
,因为它将为您的应用程序带来更多的安全性

–PDO::PARAM_STR–para valores字符串、数据、时间

–PDO::PARAM_INT–para valores inteiros

–PDO::PARAM_BOOL–para valor booleano(真或假)

–PDO::PARAM_NULL–valor nulo(NULL)

–PDO::PARAM_LOB–大量化护墙板代表

–PDO::PARAM_STMT–阿图阿门特注册公司代表 nãoésuportado por nenhum司机

< P>:PDO::PARAMI输入输出-特别是 saída para“存储过程”


$checkRecord=“从库中选择*,其中id\u gallery=“.$id这仍然容易受到SQLInjection的影响。如果要使用PDO,请不要将任何变量连接到SQL中。在这种情况下,
$\u POST['id']
foo
,由于缺少引号和准备好的语句,这将导致以下语法错误:
从gallery中选择*,其中id\u gallery=foo
~没有引号。要清楚地说,将
'
放进去没有办法解决这个问题。这可能是也可能不是正在发生的事情,但这是一种可能性。至少你应该使用
$id=(int)$\u POST['id']
intval()
检查网络选项卡,查看ajax是否正在调用并传递正确的id。如果它通过了正确的ID,则检查控件是否处于“如果”状态。你可以在每一行PHP代码中使用这个文件来调试你的代码。因此,感谢您的支持。仅供参考,MySQL PDO驱动程序会忽略PDO::PARAM类型。所有类型都像字符串一样传递给服务器。对于其他品牌的SQL数据库,这些类型在PDO驱动程序中可能更为重要。