【问题标题】:MySQLi not returning fetched dataMySQLi 不返回获取的数据
【发布时间】:2016-07-09 17:55:26
【问题描述】:

我有一个 PHP 脚本,它查询数据库并返回我数据库中所有用户名的列表。问题是,它没有打印任何东西,我认为我的 while 语句不正确,这是我下面的代码:

<?php
    include "init.php";

    $stmt = "SELECT username FROM tbl_users ";
    $result = $dbcon -> prepare($stmt);
    $result->execute();
    $result->store_result();
    $count = 0;
    while($row = mysqli_fetch_assoc($result)){
        if($row['username']=="Ben"{
          echo "Here";
        }
        //$count++;
    }

?>

即使是这样基本的东西也行不通:

<?php
    include "init.php";

    $stmt = "SELECT username FROM tbl_users ";
    $result = $dbcon -> prepare($stmt);
    $result->execute();
    $result->store_result();
    $count = 0;
    while($row = mysqli_fetch_assoc($result)){
          echo "Here";
        //$count++;
    }

?>

我似乎也无法增加计数,甚至没有打印基本的“这里”

【问题讨论】:

  • 您确定连接到数据库的用户有权查看该表吗?你确定表中有记录吗?您可以尝试“SELECT count(*) FROM tbl_users”,因为它应该返回一行(假设没有错误)。
  • 您在表格中有用户名Ben 吗?你注释掉了count++,没有$,真的是count++而不是$count++吗?
  • 嗨,本数据库中确实存在
  • 为什么要使用 oop 和程序风格? $result-&gt;fetchAll() 的输出是什么?
  • @dex -&gt;prepare() / -&gt;execute() 也是 MySQLi 方法,-&gt;store_result() 只是 MySQLi。除了while($row = mysqli_fetch_assoc($result))中的mysqli_fetch_assoc()

标签: php mysqli


【解决方案1】:

主要问题是您没有正确阅读手册/示例。

mysqli_stmt_get_result() 不会改变语句的状态。它返回 mysqli 结果。所以你必须将此返回值分配给一个变量,然后使用这个。

此外,您使用的数据库完全错误。您应该始终选择您需要的唯一数据,而不是从数据库中选择所有行。

对于您的情况,代码将是这样的。

include "init.php";
$name = "Ben";

$stmt = $dbcon->prepare("SELECT 1 FROM tbl_users WHERE username = ?");
$stmt->bind_param("s", $name);
$stmt->bind_result($found);
$stmt->execute();
$stmt->fetch();

if ($found) ... // here you go

对于其他情况,您必须仔细阅读手册或书籍。并准确地重现代码。

【讨论】:

    【解决方案2】:

    由于您的代码中有多个错误,我设法编写了一个代码我不确定以下是最好的,但它可以工作

    <?php
        include "init.php";
    
        $stmt = "SELECT username FROM tbl_users ";
        $result = mysqli_query($sqlconnection, $stmt) or die($mysqli_load->error);
        $count = 0;
        while($row = mysqli_fetch_assoc($result)){
            if($row['username']=="ben"){
              echo "Here";
            }
            //$count++;
        }
    ?>
    

    我在您的代码中发现的几个错误是 )if($row['username']=="Ben"{ 旁边缺少 "ben"){

    并使用这种类型的连接

    $link = new mysqli("localhost","user","pass","database");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      相关资源
      最近更新 更多