Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用上一个查询的结果进行查询_Php - Fatal编程技术网

Php 使用上一个查询的结果进行查询

Php 使用上一个查询的结果进行查询,php,Php,我有以下代码: $stmt = $cxn->prepare('SELECT value FROM table WHERE column = ?'); $stmt->bind_param("i", $number); $stmt->execute(); $stmt->bind_result($result); while($stmt->fetch()) { $stmt = $cxn->prepare('SELECT value FROM table2

我有以下代码:

$stmt = $cxn->prepare('SELECT value FROM table WHERE column = ?');
$stmt->bind_param("i", $number);
$stmt->execute();
$stmt->bind_result($result);

while($stmt->fetch()) {
    $stmt = $cxn->prepare('SELECT value FROM table2 WHERE column = ?');
    $stmt->bind_param("i", $result); // error on this line
    $stmt->execute();
    $stmt->bind_result($result2);
    $stmt->fetch();
}
我想在第二个查询中使用第一个查询的结果,但是,在第$stmt->bind_parami,$result;行中出现以下错误:

怎么了?

您对$cxn->prepare的第二次调用返回false或null。换句话说,第二个查询无法创建语句。正如前面提到的一条评论,这可能是由于您使用了保留字表、语法错误或连接超时等原因造成的

假设是这样,您需要检查对prepare的调用是否返回语句:

<?php
$stmt = $cxn->prepare('SELECT value FROM table WHERE column = ?');
if (!$stmt) {
    // do something to deal with the failure
    // throw new \Exception('Could not create statement');
}
$stmt->bind_param("i", $number);
$stmt->execute();
$stmt->bind_result($result);

while($stmt->fetch()) {
    $stmt = $cxn->prepare('SELECT value FROM table2 WHERE column = ?');
    if (!$stmt) {
         // failed, handle it
         // throw new \Exception('Could not create statement');
    }
    $stmt->bind_param("i", $result); // error on this line
    $stmt->execute();
    $stmt->bind_result($result2);
    $stmt->fetch();
}
如果是PDO,您可以使用和PDO::errorCode来跟踪您的问题:

<?php
$stmt = $cxn->prepare('SELECT value FROM table WHERE column = ?');
if (!$stmt) {
    var_dump($cxn->errorInfo());
    return;
}

errorInfo将返回一个数组,第一个元素是SQLSTATE代码,第二个元素是特定于驱动程序的错误代码,第三个元素是实际的错误消息。这就是开始发现查询失败的原因的地方。如果您确实将连接设置为抛出异常,则将具有所需的信息PDOException::getMessage、PDOException::$errorInfo等。

如果您使用的是实际的代码,请从表中选择值,其中列=?,表是保留的MySQL字,并且需要位于背面标记内。另外,如果你的值不是一个整数,那么它将产生一个错误,如果这不是作为值传递的内容。如果是字符串,则使用s-答案实际上在错误消息中。不要循环查询实际上,您可以在一个查询中完成所有操作。更高效更安全。不,它们只是我输入的位置值。它们在我的实际代码中是不同的。是的,它返回false,但我不知道为什么。请参阅我的编辑:如果是PDO,您可以使用errorInfo开始跟踪它。因此,我不得不添加$stmt->close;在第一次询问之后,但我不知道为什么。你能解释一下吗?
<?php
$cxn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

// after the above, failing calls to $cnx->prepare will throw exceptions
<?php
$stmt = $cxn->prepare('SELECT value FROM table WHERE column = ?');
if (!$stmt) {
    var_dump($cxn->errorInfo());
    return;
}