简体   繁体   English

使用数组变量的Foreach循环中的SQL查询

[英]SQL query in Foreach loop using array variable

UPDATE: 更新:
WORKING CODE, Thanks jon for the push in the right direction. 工作代码,谢谢乔恩朝着正确的方向前进。

<?php

     $stmt2 = $conn->prepare("SELECT * FROM userItems WHERE id=:id");

        foreach ($moodItems as $id2)
            {

    // bind the parameters
        $stmt2->bindValue(":id", $id2);    

      if ($stmt2->execute()) {

            if($result = $stmt2->fetch(PDO::FETCH_ASSOC)) {

    // initialise an array for the results 
            $itemName2 = $result['itemName'];
                $name2 = $result['userId'];
              echo $itemName2."<br>";
              echo $name2."<br>";
        }
     }
   }   
      ?>

I am having trouble using a SQL query in a foreach loop. 我在foreach循环中使用SQL查询时遇到问题。 I am trying to use the value from the first query(which is an array) and use it in the second query. 我正在尝试使用第一个查询(它是一个数组)中的值,并在第二个查询中使用它。

The first query works correctly to give me the proper value(array).But for some reason when I try to use the array in the foreach it does not work properly, it does not show any errors...it just does not fetch any data from the database. 第一个查询可以正确地给我正确的值(数组),但是由于某些原因,当我尝试在foreach中使用数组时,它不能正常工作,它不会显示任何错误...它只是无法获取任何内容数据库中的数据。
IE/ echo $itemName2; IE / echo $ itemName2; <----does not get any info from database <----没有从数据库中获取任何信息

Any help would be great. 任何帮助都会很棒。 Thanks. 谢谢。

here is the code I am working with: 这是我正在使用的代码:

<?php           
$attrs = array(PDO::ATTR_PERSISTENT => true);

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare the statement.
$stmt = $conn->prepare("SELECT * FROM userMoodboard WHERE name=:name");

// bind the parameters
$stmt->bindValue(":name", $loggedInUser->username);

// initialise an array for the results 
if ($stmt->execute()) {

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $imageUrl = $row['imageUrl'];
            $moodItems = $row['moodItems'];
            $moodItems = json_decode($moodItems);

?>
<img src='<?php echo $imageUrl;?>' class="thumbnail"></img>
    <?php
    $stmt = $conn->prepare("SELECT * FROM userItems WHERE id=:id");

        foreach ($moodItems as $id)
               {
    // bind the parameters
        $stmt->bindValue(":id", $id);    

    // initialise an array for the results 
        if($stmt->execute()) {
            $itemName2 = $row['itemName'];
                $name2 = $row['userId'];

              echo $itemName2;
              echo $name2;
        }
        }   

    }

    }
?>

There are a couple of things wrong with your code, but we'll start with your second statement. 您的代码有很多问题,但是我们将从您的第二条语句开始。

$stmt = $conn->prepare("SELECT userId FROM userItems WHERE id=:id");

foreach ($moodItems as $id)
{
    // bind the parameters
    $stmt->bindValue(":id", $id);    

    // initialise an array for the results 
    if($stmt->execute()) {
        $itemName2 = $row['itemName'];
        $name2 = $row['userId'];

        echo $itemName2;
        echo $name2;
    }
}

You are trying to pull out $row['itemName'] and $row['userId'] , however, you never SELECT the itemName column in that query. 您试图拉出$row['itemName']$row['userId'] ,但是,您从不SELECT该查询中的itemName列。 So if you want that information, you'll have to select it first. 因此,如果您需要该信息,则必须首先select它。 Aside from that, you execute the query, but you never fetch the row with information. 除此之外,您还execute查询,但从未fetch信息行。

Those are the basics of why the second portion will not work how you want it to. 这些就是为什么第二部分无法按您希望的那样工作的基础。

Now, for the bigger picture. 现在,为大局。 Most of the block of code you provide is a nested if for your first $stmt->execute() and then within a while($row = ... Which, by itself is fine. However, later within the same block, you prepare another statement, which is perfectly acceptable, but you assign it to the same $stmt variable that you are using for the loop in the first place, which will also cause you problems. You'll want to assign a new variable for your second prepared statement, so you can work with the new data-set. Also, going back to the previous block I posted in, you'll want to fetch it to a variable that is not $row , as that is also a used variable. if为您的第一个$stmt->execute()然后在while($row = ... $stmt->execute() ,您提供的大多数代码块都是嵌套的,这本身很好,但是,稍后在同一块中,您可以准备另一条语句,这是完全可以接受的,但是首先将其分配给用于循环的相同$stmt变量,这也会引起问题,您将需要为第二个变量分配一个新变量准备好的语句,因此您可以使用新的数据集。此外,返回到我之前发布的上一个块,您将希望将其获取到不是 $row的变量,因为它也是一个使用过的变量。

UPDATE: As pointed out by Jon, my answer applies to Zend_Db_Adapter and not to PDOStatement (which you are using). 更新:正如乔恩指出的那样,我的答案适用于Zend_Db_Adapter而不适用于PDOStatement(您正在使用)。 My apologies. 我很抱歉。

The problem probably is that you're doing $stmt->execute() on the second SQL query. 问题可能是您正在第二个SQL查询上$stmt->execute() execute() does not return results, what you want to do is to fetch() , which does return results. execute()不返回结果,您要做的是fetch() ,它确实返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM