我是PHP和MySQL的新手,我正在寻找一种解决方案,使用预准备语句在变量中存储数据库行的单个值。
现在这是准备好的声明和执行:
$emailsql = $conn->prepare("SELECT email FROM User WHERE email = ? limit 1;");
$emailsql->bind_param('s', $email);
$emailsql->execute();
我尝试了get_result()
,fetch()
,fetch_object()
,但我没有想法和谷歌搜索结果。
答案 0 :(得分:1)
您需要在代码中添加结果与特定变量的绑定
$emailsql->bind_result($emailResult);
你拿到它:
while($emailsql->fetch()){
printf ($emailResult);
}
所以这应该是它:
$emailsql = $conn->prepare("SELECT email FROM User WHERE email = ? limit 1;");
$emailsql->bind_param('s', $email);
$emailsql->execute();
$emailsql->bind_result($emailResult);
while($emailsql->fetch()){
printf ($emailResult);
}
如果您需要循环外的变量,我会采用这种方法:
$theEmail;
$emailsql = $conn->prepare("SELECT email FROM User WHERE email = ? limit 1;");
$emailsql->bind_param('s', $email);
$emailsql->execute();
$emailsql->bind_result($emailResult);
while($emailsql->fetch()){
$theEmail=$emailResult;
}
请注意,您需要一个数组才能查询多个电子邮件。
@YourCommonSense建议的另一种清洁方法是避免这样的循环:
$theEmail;
$emailsql = $conn->prepare("SELECT email FROM User WHERE email = ? limit 1;");
$emailsql->bind_param('s', $email);
$emailsql->execute();
$emailsql->bind_result($emailResult);
$emailsql->fetch();
printf($emailResult);
希望这有助于你
答案 1 :(得分:0)
你可以同时使用get_result()和fetch(),但是对于一个变量,后者需要更少的代码来编写,尽管它确实看起来不自然:
假设您已经收到了一封电子邮件而且您正在寻找一个标志,看看是否有这样的用户,代码将是
$stmt = $conn->prepare("SELECT 1 FROM User WHERE email = ? limit 1;");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->bind_result($found);
$stmt->fetch();
if ($found) {
// do whatever
}
请注意,您应该避免在另一个答案中建议的不必要的循环,因为它会使代码无缘无故地复杂化。
鉴于这一切,与PDO相比,您可以考虑bad mysqli usability:
$stmt = $conn->prepare("SELECT 1 FROM User WHERE email = ? limit 1;");
$stmt->execute([$email]);
$found = $stmt->fetchColumn();
if ($found) {
// do whatever
}