将mysqli转换为PDO获取错误

时间:2014-11-22 17:45:41

标签: php pdo mysqli

我正在尝试将MySQL转换为pdo,但我一直在PDO上得到一个错误,任何想法我可能做错了什么。 MySQL正在运行,只有pdo我才会收到错误。

<?php


header('Content-Type: application/json');



$db_conx = mysqli_connect("localhost", "root", "", "employees_db");

$lanId=  $_POST["lanId"];
       $sql="SELECT * FROM  names WHERE LanID='$lanId'   "; 
        $query= mysqli_query($db_conx, $sql);

    $row = mysqli_fetch_array($query, MYSQLI_ASSOC);
    $rc= $row["FIRSTNAME"]. " " . $row['LASTNAME'];

echo json_encode ($rc);

?>

这是PDO版本。

<?php

header('Content-Type: application/json');

// PDO
$pdo = new PDO("mysql:host=localhost;dbname=employees_db", 'root', '');
$lanId=  $_POST["lanId"];       
        $params = array( ':LanID' => $lanId);

$pdo->prepare("
    SELECT * FROM names
    WHERE LanID='$LanID'");

$pdo->execute($params);

$result = $pdo->fetch(PDO::FETCH_ASSOC);

    $rc= $result->FIRSTNAME. " " . $result->LASTNAME;

echo json_encode ($rc);

?>

这里是带有ajax的Json,当你在id到lanId文本框中输入id时,它会检索文本框名称中的姓氏和名字

$(document).ready(function(){
      $("#lanId").change(function(){
          var lanId=$(this).val();
           if(lanId != ''){
                  $.ajax({
                              type:"post",
                              url:"insert.php",
                              data:"lanId="+lanId,
                              datatype:"json",
                              success:function(data){ $("#name").val(data);
                                $('#name').css( "background-color","#B3CBD6"  ) 
                               $('#name').animate({backgroundColor: "#ffffff"});
                               },
                                 error: function(response){
    alert("error scripting")    }

                                                           });
           }
           else{
               $("#name").val("");
               }

          });
     });

1 个答案:

答案 0 :(得分:4)

$pdo->prepare("
    SELECT * FROM names
    WHERE LanID='$LanID'");

这应该是

$query = $pdo->prepare("
    SELECT * FROM names
    WHERE LanID=:LanID");

然后使用

$query->execute($params);

在这里查看示例2 http://php.net/manual/en/pdostatement.execute.php

编辑:完整代码:

<?php

header('Content-Type: application/json');

// PDO
$pdo = new PDO("mysql:host=localhost;dbname=employees_db", 'root', '');
$lanId=  $_POST["lanId"];       
        $params = array( ':LanID' => $lanId);

$query = $pdo->prepare("
    SELECT * FROM names
    WHERE LanID=:LanID");

$query->execute($params);

$result = $query->fetch(PDO::FETCH_ASSOC);

$rc= $result['FIRSTNAME'] . " " . $result['LASTNAME'];

echo json_encode ($rc);

?>