0

我试图理解这个 SQL 语句:

$id = 5;

$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');

    $stmt->execute(array('id' => $id));

    while($row = $stmt->fetch()) {
        print_r($row);
    }

有人可以逐步解释一下这里到底发生了什么吗?

据我了解:

$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');

1) $stmt 即将作为 iinput 一个 SQL 查询。SQL 查询是从一个表中选择其 id 等于 5 的所有行。

$stmt->execute(array('id' => $id));

2) 我们执行语句。现在 $stmt 有这些行?

$row = $stmt->fetch()

3) 这对我来说是最令人困惑的一行。这里到底发生了什么?变量“行”一一获取 id = 5 的行?这就是 fetch() 的作用吗?如果是,它返回结果的准确程度如何?它是所有正确答案的数组?例如,所有 id = 5 的行?我不明白这个while循环在这里是如何工作的。它第一次运行“行”时会有第一行吗?第二次运行时,将有第二行满足我们的条件(id = 5)等等?每次我运行 fetch 时都会返回一个结果吗?下次我运行 fetch 时,下一个结果,直到没有更多结果可以满足查询?

我觉得我很接近得到这个。任何可以帮助我完全理解它的东西都将不胜感激!

4

2 回答 2

4

我将解释为评论:

$id = 5;

// Create a prepared statement - don't actually execute the statement yet. 
// The :id value in the statement will be replaced by a parameter value (safely) when the
// statement is executed
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');

// Execute the statement against the DB - the $stmt var now contains the result set for the
// executed statement. e.g. it contains *all* the results that the query fetched
$stmt->execute(array('id' => $id));

// Now we loop through the rows in the result set (they are all in memory at this point). 
// "fetch" will start from row 1 and return the next result each time you call it again. 
// when there are no more rows it returns FALSE and therefore breaks out of the while loop
while($row = $stmt->fetch()) {
    print_r($row);
}

也只是检查文档,虽然这是以前的做法(自从我接触 PHP 以来已经有好几年了),它看起来stmt->fetch()实际上将结果放入绑定变量中:

http://php.net/manual/en/mysqli-stmt.fetch.php

$row = array();
stmt_bind_assoc($stmt, $row);

// loop through all result rows
while ($stmt->fetch()) 
{
    print_r($row);
}

您最初发布的代码是否真的有效?您似乎没有绑定任何变量,因此由于$stmt-fetch()调用返回 bool TRUE/FALSE,它似乎$row不会被设置为除 TRUE/FALSE 之外的任何值

于 2013-05-02T09:28:30.857 回答
2

这里它使用 PDO 执行,

使用准备好的语句重复 SELECT,您可以通过这些语句调用重复查询

$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');

:id它定义了占位符在哪里的准备好的语句

$stmt->execute(array('id' => $id));

这个地方将值分配给占位符并执行查询

$row = $stmt->fetch()

它从选择中获取记录

如需更多参考,请访问链接 http://www.php.net/manual/en/pdo.prepared-statements.php

于 2013-05-02T09:32:12.590 回答