如何在PHP变量中存储MySQLi准备语句中单行的单列?
我对PHP和MySQL还是很陌生,我正在寻找一种解决方案,以使用准备好的语句将数据库行的单个值存储在变量中.
I'm very new to PHP and MySQL and I'm looking for a solution to store a single value of a database row in a variable using a prepared statement.
现在这是准备好的语句和执行:
Right now this is the prepared statement and execution:
$emailsql = $conn->prepare("SELECT email FROM User WHERE email = ? limit 1;");
$emailsql->bind_param('s', $email);
$emailsql->execute();
我尝试了get_result()
,fetch()
,fetch_object()
,但我的想法和Google搜索结果都没有了.
I tried get_result()
, fetch()
, fetch_object()
and I'm out of ideas and google search results.
您需要将结果与特定变量的绑定添加到代码中
You need to add to your code the binding of the result to a specific variable
$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);
}
如果您需要循环外的变量,我会采用这种方法:
In case you need the variable outside the loop I would take this approach:
$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;
}
请注意,您需要一个数组才能查询多个电子邮件.
Note that you would need an array in order to query more than one email.
@YourCommonSense建议的另一种更清洁的方法是避免像这样的循环:
Another cleaner approach as @YourCommonSense suggested would be avoiding the loop like so:
$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);