简体   繁体   中英

implode or explode mysql_fetch_array in php

Hi guys. I'm currently try to make an mysql query than take the results and use them in an another query. So I thought I'm calling my database and use mysql_fetch_array and than implode it do insert , so I can use it in an another query. I read here many questions about this and based on the questions i wrote my own piece of code but I'm getting this error:

Warning: array_values() expects parameter 1 to be array, string given in /var/www/html/lager_management/warenkorb.php on line 107

Warning: implode(): Invalid arguments passed in /var/www/html/lager_management/warenkorb.php on line 108

Here is the piece of code what is going wrong I can't explain myself and I know mysql is old and I should use myqli

$sql3 = "SELECT `Index` FROM lm_Warenkorb;";
        $result3 = mysql_query($sql3);
        while($resultarray3 = mysql_fetch_array($result3)) 
        {
        $anfrage = array();
        $anfrage = $resultarray3['Index'];
        $anfrage = implode(", ", $anfrage); 

          $sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".$anfrage.");";
        }

The table lm_Warenkorb looks like this:

Index:
    10
    2
    6

you use mysql_fetch_array($result) in a while loop, which is perfectly right.

But this obviously will only return one row of your table from database and not the whole column.

therefore $resultarray3['Index']; returns the value of Index column of your first table row, which is not an array.

Try this

$anfrage = array();
while($resultarray3 = mysql_fetch_array($result3)) 
{
 $anfrage[] = $resultarray3['Index'];
}

if(count($anfrage) > 0) {
  $anfrage = implode(",", $anfrage); 
  $sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".$anfrage.");";
}

I think you could do it using one query with nested SELECT:

 $sql3 = "
SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` 
    FROM `lm_Artikel` 
    WHERE `Index` IN (
      SELECT `Index` FROM lm_Warenkorb
    )";

        $result3 = mysql_query($sql3);

        while($resultarray3 = mysql_fetch_array($result3)) {
          // handle the results
        }
$sql3 = "SELECT `Index` FROM lm_Warenkorb;";
$result3 = mysql_query($sql3);
$data = array(0);
while($resultarray3 = mysql_fetch_assoc($result3))
{
    $data[] = $resultarray3['Index'];
}
$sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".implode(',', $data).");";
echo $sql2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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