未能正确使用mysqli准备好的语句

时间:2012-12-31 03:28:18

标签: php mysqli

我正在学习php和mysqli,

我希望打印出mysql查询的结果 到目前为止,我已经这样做了:

$link = mysqli_connect("host","user", "pass","db_name");
//error handling here
//printing host info here
$company_name = "ODEON";
$query = "select company from production where company = ?";
$stmt = mysqli_stmt_init($link);
if (!($stmt = mysqli_stmt_prepare($stmt, $query))){
     echo "Prepare failed: (" . $stmt->errno . ") " . mysqli_error($link);
}
var_dump($stmt); //for debugging
echo "before bind<br>";
if(!(mysqli_stmt_bind_param($stmt, "s", $company_name))){
    echo "Binding parameters failed: (" . $stmt->errno . ") " . mysqli_error($stmt);
}
echo "after bind<br>";
var_dump($stmt); //for debugging

if(!(mysqli_execute($stmt))){
    echo "Execute failed: (" . $stmt->errno . ") " . mysqli_error($stmt);  
}

printf("<hr>Results:<br>");
while($obj = mysqli_fetch_object($result)){
    printf("%s<br>", $obj->company_name);
}
mysqli_free_result($obj);
printf("<hr><br>");

mysqli_stmt_close($stmt);
mysqli_close($link);

我得到的就是这个:

Host information: host via TCP/IP
Prepare failed: (0) NULL 
Binding parameters failed: () NULL 
Execute failed: () 

有什么问题?

2 个答案:

答案 0 :(得分:1)

我认为问题在于您使用mysqli_stmt_prepare

你正在传递$link但是你需要在声明中传递。您需要致电$stmt = mysqli_stmt_init($link);并改为通过$stmt

从PHP文档剪切:

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, 'SELECT District FROM City WHERE Name=?')) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

答案 1 :(得分:1)

终于解决了。 问题是我使用localhost时没有发布任何错误。 所以,在我位于

的php.ini文件中
  

/usr/local/zend/etc/php.ini

(由于安装了zend框架) 将显示错误更改为开..

代码的问题可能在这里:

  

$ stmt = mysqli_stmt_prepare($ stmt,$ query)

使用第一个参数,这是不需要的。