我知道这个特定的查询是有效的,因为我用未经准备的过程方法测试了它。这里是:
$name = 'introduction';
$mysqli = new mysqli('localhost', 'user', 'pass', 'db') or die('There was a problem connecting to the database.');
$stmt = $mysqli->prepare("SELECT name, content FROM sections WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($content);
$stmt->fetch();
echo $content;
$stmt->close();
我意识到,由于我有一个 id 列作为节表中的索引,因此我也需要根据 php.net 上的上述语句将其绑定(再次感谢 Bill)。
这是新代码:
$name = 'introduction';
$mysqli = new mysqli('localhost', 'user', 'pass', 'db') or die('There was a problem connecting to the database.');
$stmt = $mysqli->prepare("SELECT name, content FROM sections WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($id, $name, $content);
$stmt->fetch();
echo $content;
$stmt->close();
再次感谢所有能够提供建议的人。 (我很好奇:我发现以这种方式使用 OOP 风格的准备好的语句时很难进行调试。例如,是否有一种简单的方法来简单地查看实际使用的查询?)
如果我执行以下操作,就像一个简单的例子:
$name = 'introduction';
@mysql_connect('host', 'user', 'pass');
@mysql_select_db('db');
$query = "SELECT name,content FROM sections WHERE name = '$name'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_object($result)) {
$content = $row->content;
echo $content;
}
我的数据出现了,一切都很好。但是,如果我执行以下操作:
$name = 'introduction';
$mysqli = new mysqli('localhost', 'user', 'pass', 'db') or die('There was a problem connecting to the database.');
$stmt = $mysqli->prepare("SELECT name, content FROM sections WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($name, $content);
$stmt->fetch();
echo $content;
$stmt->close();
我认为这是正确的(当然,如果不正确,请随意大喊大叫),我什么也没得到。更重要的是,使用该代码,当我进行 html 验证(以防万一)时,我收到内部服务器警告 (500),我认为这是 sql 代码的问题。我只是疯了吗?