0

首先,这是我第一次接触 MySQLi... 听说 MySQLi 比较好,但是每次我写一些代码,我都得到

致命错误:在非对象上调用成员函数 bind_param()

我的代码是这样的:

<?php
/* Create a new mysqli object with database connection parameters */
$m = new mysqli('localhost', 'root', '', 'mysqlisample');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$ida=1;
$statement = $m->prepare("SELECT * FROM post WHERE `id` =  ?");
$statement->bind_param("i",$ida);
$id = 0;
$post_title = '';
$post_content = '';
$statement->bind_result($id,$post_title,$post_content);
$statement->execute();
while ($statement->fetch()){
echo $id.' '.$post_title.' '.$post_content.'\n'; //These variables will get the values of the current row
}
?>

这只是我在某处读到的许多代码示例之一,但是它们都不起作用。

执行 MySQLi 查询并打印结果的正确方法是什么?

4

2 回答 2

1

我在阅读 OReilly 的书时解决了这个问题,该书使用的是旧的 mysql_stuff 并且没有一个示例有效。显然你需要为你的表修改它:) 但它适用于我拥有的表。这将适用于准备好的陈述:

<?php

//this file is just where my db info is, you can use the literal values
require 'login.php';

$db = new mysqli($db_hostname, $db_username, $db_password, $db_database);
$stmt = $db->stmt_init();
$data = array("Emily Bronte", "Wuthering Heights", "Classic Fiction", "1847", "9780553212587");

if($stmt->prepare("INSERT INTO classics(author, title, category, year, isbn) VALUES(?,?,?,?,?)"))
{
    $stmt->bind_param('sssss', $data[0], $data[1], $data[2], $data[3], $data[4]);
    $stmt->execute();
    $stmt->close();
}

?>

这将适用于查询:

<?php
require_once 'login.php';
$dbt = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($dbt->connect_errno) 
    die("Unable to connect to MySQL: " . $dbt->connect_errno);

$results = $dbt->query("SELECT * FROM cats");

if (!$results) 
    die ("Database access failed: " . $db->error);

$dbt->close();

echo "<table><tr> <th>Id</th> <th>Family</th>
<th>Name</th><th>Age</th></tr>";

for ($j = 0 ; $j < $results->num_rows ; ++$j)
{
    $row = $results->fetch_row();
    echo "<tr>";
    for ($k = 0 ; $k < sizeof($row) ; ++$k) 
        echo "<td>$row[$k]</td>";
    echo "</tr>";
}
echo "</table>";

?>
于 2013-02-05T14:56:12.907 回答
0

问题是$statement->bind_param("i",$ida);返回false,所以你不能调用该bind_param方法false

见: http: //php.net/manual/de/mysqli.prepare.php

尝试:

mysqli_stmt_bind_param($statement, "i", $ida);

代替:

$statement->bind_param("i",$ida);
于 2013-02-05T14:51:30.250 回答