【问题标题】:Why does one php statement work and the other doesn't?为什么一个 php 语句有效而另一个无效?
【发布时间】:2023-03-21 06:17:01
【问题描述】:

在下面的 sn-p 中,我了解到 mysqli_fetch_row 仅适用于列索引(0、1、2 等),而不适用于列名。

但我考虑使用列号/排序不好的做法(如果顺序发生变化怎么办?)。

如何返回单行,然后使用列名获取数据?

  $query = "Select * from users where UserEmail = '" . $UserEmail . "' LIMIT 1";

  $result = mysqli_query($connection, $query);

  $num_rows = mysqli_num_rows($result);
  $row = mysqli_fetch_row($result);

  $arr = $result->fetch_assoc();
  $log->lwrite('Works / value: ' . $row[0]);
  $log->lwrite('Does not work / value: ' . $arr['userID']);

【问题讨论】:

  • 使用while 循环并为您要引用的每一列分配一个变量。
  • 但是“限制 1”保证我只能得到一排...也许这就是我的心智模型与现实不符的地方:)
  • 是的,没关系 ;-) 你可以使用 LIMIT 1, 10 的偏移量
  • ?所以即使只有一行我也需要做一个循环?
  • 不,不是真的,但理论上你可以,如果你想引用某一行。

标签: php mysqli


【解决方案1】:

它不起作用,因为 fetch_row 将结果的指针移动到第二行。并且没有第二行,因为您的查询中有 LIMIT。

只需删除第一次提取就足够了。

$query = "Select * from users where UserEmail = '" . $UserEmail . "' LIMIT 1";

$result = mysqli_query($connection, $query);

$arr = mysqli_fetch_assoc($result);
$log->lwrite('Does work now / value: ' . $arr['userID']);

同时将面向对象的风格与程序风格混合被认为是不好的做法。我这里用的是第二个。

【讨论】:

  • 非常感谢!我没有意识到我使用 $row = mysqli_fetch_row($result);干扰了应该是简单的语法(提取特定字段/列)。
猜你喜欢
  • 2019-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2011-02-11
相关资源
最近更新 更多