我正在尝试为下面的MySQL查询调整以下代码,但无法解决如何执行此操作。查询应该只返回一行,我想从该行的“代码”列中提取数据,并将其作为变量传递给我的PHP脚本。
/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code from Clients where Name='Jane'")) {
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($code);
/* fetch values */
while ($stmt->fetch()) {
printf($code);
}
/* close statement */
$stmt->close();
}
答案 0 :(得分:1)
我认为你一直在http://php.net/manual/en/mysqli.prepare.php的基础上工作。但是,您也应该对绑定参数进行跟踪:
/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code from Clients where Name=?")) {
/* bind query parameters to prepared statement */
$stmt->bind_param("s", 'Jane');
$stmt->execute();
/* bind result variables to prepared statement */
$stmt->bind_result($code);
/* fetch values */
if ($stmt->fetch()) {
printf('Code: %s', $code);
} else {
print("Client code was not found");
}
/* close statement */
$stmt->close();
}
你在这里准备陈述,所以你应该单独绑定你的params。
答案 1 :(得分:0)
一起去:
if ($stmt = $mysqli->prepare("SELECT Code from `Clients` where Name = 'Jane' LIMIT 1")) {
$stmt->execute();
$stmt->bind_result($code);
$stmt->fetch();
$stmt->close();
}
在脚本末尾$code
将包含Code
列中的数据。
答案 2 :(得分:0)
您可以将代码更改为以下内容:
$value = $stmt->fetch();
此外,如果您知道要从数据库中获取单个值,则可以通过在sql语句末尾执行'limit 1'
来加快速度。
答案 3 :(得分:0)
不要为这么小的操作浪费太多代码。看,这几乎是整个屏幕! 如果您的代码中需要十几个变量怎么办? 将所有代码封装到辅助函数中,然后在一行中将其称为:
$code = $db->getOne("SELECT Code from Clients where Name='Jane'");