【问题标题】:Retrieving data from database using prepared statement使用准备好的语句从数据库中检索数据
【发布时间】:2016-01-29 13:47:10
【问题描述】:

我在从数据库中检索数据时遇到问题。这是我的代码:

function login($email, $password) {
    $stmt = $this->conn->prepare("SELECT id FROM lms_admin_users WHERE email=?");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $stmt->store_result();
    if($stmt->num_rows == 1) {
        while ($stmt->fetch()) {
            // echo data from table like $data["name"]; <----
        }
    }
    else {
        echo "Failed";
    }
}

我想知道的是相当于while($data=mysqli_fetch_assoc($result)) 来替换我现有的代码(以OOP 方式)while ($stmt-&gt;fetch()) 并使其使用$data["name"] 获取数据

【问题讨论】:

  • 请描述您遇到的错误,到目前为止一切正常。检查$stmt === false是否在你准备好语句后立即检查来自数据库的错误消息($this-&gt;conn-&gt;error
  • 好的,我想知道的是相当于while($data=mysqli_fetch_assoc($result)) 用于OOP 准备好的语句。我没有收到任何错误,我的问题是我无法使用 while ($stmt-&gt;fetch())while ($data=$stmt-&gt;fetch()) 获取我的数据
  • 您的问题目前尚不清楚,您的问题确实是您不知道在到达while 循环后如何访问检索到的数据。请把这个放在你的问题中,因为它可能会因为不清楚而很快被关闭。

标签: php database oop fetch


【解决方案1】:

您需要告诉 PHP 将结果存储在哪个变量中。有两种方法可以做到这一点:

  1. 使用bind_result,然后在语句对象上使用fetch,或者
  2. 在结果对象上使用get_result,然后是fetch_assoc(或其他fetch_* 变体)

1。绑定结果

使用此解决方案,您可以将变量绑定到SELECT 列表,并且在使用fetch 循环时,PHP 会将新数据放入这些变量中:

$stmt = $this->conn->prepare("SELECT id FROM lms_admin_users WHERE email=?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();    
$stmt->bind_result($id, $name);  // <- Add; #args = #cols in SELECT
if($stmt->num_rows == 1) {
    while ($stmt->fetch()) {
        echo $id, $name;  // <-- then you can do this.
    }
}

2。获取结果

您可以使用get_result 代替bind_result,这将提供一个结果对象,您可以从该对象中获取每一行作为关联数组:

//...
//  $stmt->store_result();   // <- Remove: does not work together with next statement
$result = $stmt->get_result();   // <--- add this instead
if($result->num_rows == 1) {     // <--- change to $result->...!
    while ($data = $result->fetch_assoc()) {
        echo $data['id'], $data['name'];  // <--- available in $data
    }
}

【讨论】:

  • 第一个解决方案对我有用,但即使我更改变量它也只能获取 ID,第二个解决方案给我一个错误Fatal error: Call to a member function fetch_assoc() on boolean in C:\laragon\sad\admin\inc\class.library.php on line 32。我需要if($stmt-&gt;num_rows == 1) 使用提供的电子邮件地址验证该用户是否存在,然后它将转到while ($stmt-&gt;fetch()) 语句以获取密码数据,以便我能够使用password_verify() 函数并为用户提供会话进入会员专区。非常感谢您的帮助。
  • 您能否使用在 SELECT 列表中有多个字段的 SELECT 语句更新您的问题,以便我可以调整我的答案? Fatal error 表示对 get_result 的调用失败:我更正了我的答案。显然store_resultget_result 不能在这种组合中使用。我还添加了 num_rows 调用,这在第二个解决方案中有所不同。
  • 我尝试了第二个选项,它有效!我只是将 SQL 查询中的某些内容从 id 更改为 *.非常感谢,你救了我!
  • 好的,感谢您这样做。如果您提出新问题并希望我也查看它,请在创建问题后随时在这些 cmets 中发布指向它的链接。这样我会收到通知。
  • 我有一个新问题,请看一下:stackoverflow.com/questions/35091778/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
相关资源
最近更新 更多