mysql - 为什么两个不同的 mysql 函数在对从单个 mysql_query() 检索的数据执行时返回不同的行?

标签 mysql

我尝试将此作为测试目的。我不知道为什么会发生这种情况。这就是我需要专家的帮助。谢谢。

假设我们有一个数据库并且已经与该数据库建立了连接。假设有一个名为 table 的表。表内有两列 - id 和 name。表中有5行数据。表结构为

| id |  name  |
---------------
| 1  |  name1 |
| 2  |  name2 |
| 3  |  name3 |
| 4  |  name4 |
| 5  |  name5 |

现在我的代码放在这里-

    <?php
    mysql_connect("localhost","root","") or die(mysql_error());
    mysql_select_db("test") or die(mysql_error());

    $result  = mysql_query("SELECT * FROM `table`");

    /* let's store this value in two different variables. */

    $result1 = $result;
    $result2 = $result;

    /* let's perform mysql_fetch_array() and mysql_fetch_row() functions */
    $result22 = mysql_fetch_row($result);
    var_dump($result22);
    $result11 = mysql_fetch_array($result);
    var_dump($result11);
?>

结果:

array
  0 => string '1' (length=1)
  1 => string 'name1' (length=5)

array
  0 => string '2' (length=1)
  'id' => string '2' (length=1)
  1 => string 'name2' (length=5)
  'name' => string 'name2' (length=5)

如果我改变函数的顺序,则会产生结果:

array
  0 => string '1' (length=1)
  'id' => string '1' (length=1)
  1 => string 'name1' (length=5)
  'name' => string 'name1' (length=5)

array
  0 => string '2' (length=1)
  1 => string 'name2' (length=5)

似乎当我对 mysql_query 的结果执行函数时,该函数只是从结果中删除第一行,即使它之前存储在其他变量中 调用该函数。

如果我添加一个条件 WHERE id = 1 那么第二个函数返回 false,例如:

array
  0 => string '1' (length=1)
  'id' => string '1' (length=1)
  1 => string 'name1' (length=5)
  'name' => string 'name1' (length=5)

boolean false

为什么会发生这种情况?提前致谢。

最佳答案

该行不返回“结果”,它返回 resource您可以用来访问结果的对象:

$result = mysql_query("SELECT * FROM `table`");

这些行只是将相同的资源分配给两个不同的变量:

$result1 = $result;
$result2 = $result;

您不应将其视为两个单独的结果集。您刚刚为同一资源指定了两个不同的名称。

关于mysql - 为什么两个不同的 mysql 函数在对从单个 mysql_query() 检索的数据执行时返回不同的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10355529/

相关文章:

mysql - 在 MySQL 中获得最高分

Java JDBC UPDATE 添加号码?

php - redbean php 是否考虑创建 mysql-triggers?

php - MySQL 查询正确组合这些表

mysql - 嵌套 CONCAT 中的 LEFT JOIN 和 IS NULL 仅返回 NULL

sql - 第 3 方 sql 导入在导入 sql 文件时停止,出现错误 : #1068 - Multiple primary key defined

mysql - Rails 查询不同的顺序取决于列

python - Django:访问模板中的列表属性

php - 将数据从数组插入数据库

php - 计算多行的两个数据库值之间的时间差