如何在PHP变量中存储MySQLi准备语句中单行的单列? [英] How to store a single column of a single row out of a MySQLi prepared statement in a PHP variable?

查看:57
本文介绍了如何在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);

这篇关于如何在PHP变量中存储MySQLi准备语句中单行的单列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆