Mysqli“准备语句”不是创建对象

时间:2011-04-06 10:55:02

标签: php mysql mysqli prepared-statement

我是一个但未使用Mysqli,我遇到以下代码的问题..

$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database');
     if (mysqli_connect_errno()) {
        printf("DB error: %s", mysqli_connect_error());
        exit();
     }

     $query = "INSERT INTO employee(id, name, age, address, phone, email, department,
         designation, joindt, terminate, salary, deduction, tds, pf)
         VALUES (:id, :name, :age, :address, :phone, :email, :department,
         :designation, :joindt, :terminate, :salary, :deduction, :tds, :pf)";

     $ins = $mysql->prepare($query);
     if(!ins){
            echo "prepare failed\n";
      echo "error: ", $mysql->error, "\n";
      echo "OBJECT NOT CREATED";
      return;

     }

运行此代码后,我的浏览器出现以下错误:

  

(!)致命错误:未捕获异常'mysqli_sql_exception'   消息'你的错误   SQL语法;检查手册   对应于您的MySQL服务器   用于正确语法的版本   靠近'in   C:\ wamp \ www \ payroll \ new_backend.php on   第40行

     

(!)mysqli_sql_exception:你有   SQL语法中的错误;检查   与您的MySQL对应的手册   用于正确语法的服务器版本   使用附近'加入,终止,工资,   演绎,tds,pf)VALUES(:id,   :name,:age,'在C:\ wamp的第2行   \ www \ payroll \ new_backend.php就行了   40

我猜PREPARE语句没有创建$ ins对象。有什么帮助吗?

3 个答案:

答案 0 :(得分:5)

join是mySQL中的保留字。你需要将它包含在反引号中:

`join` 

或 - 更好 - 更改列的名称。

此外,看起来mysqli不支持PDO风格的:fieldname绑定。查看manual on prepare().

中的示例

我现在无法测试,但正确的语法应该是这样的(缩写):

$id = 10;
$name = "John Doe";

$query = "INSERT INTO employee(id, name) values (?, ?)";
$query->bind_param("i", $id);
$query->bind_param("s", $name);

答案 1 :(得分:1)

查看mysqli :: prepare()的手册页:

准备好的语句希望?成为占位符,而不是:foo

答案 2 :(得分:1)

这是我在Pekka的帮助下到达的解决方案.. :)

 $mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database');
     if (mysqli_connect_errno()) {
        printf("DB error: %s", mysqli_connect_error());
        exit();
     }

     $query = "INSERT INTO employee(name, age, address, phone, email, department,
         designation, joindt, terminate, salary, deduction, tds, pf)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";

     $ins = $mysql->prepare($query);
     if(!$ins){
            echo "prepare failed\n";
      echo "error: ", $mysql->error, "\n";
      return;

     }

     $ins->bind_param('sisisssiiiiii', $data['name'], $data['age'], $data['address'],
             $data['phone'], $data['email'], $data['department'], $data['designation'],
             $data['joindate'], $data['terminationdate'], $data['salary'], $data['leave_deduction'], $data['tds'], $data['pf']);

     $ins->execute();