简体   繁体   中英

Select from table where clause from array from another table

I'm trying to insert a failsafe into a code to prevent them from going a step further, and I've been scratching my head for a while now. I am able to put something into an array, but I am not able to get the items from the array to match the second select query. I only get Array instead of the value from the item.

My first select query is this:

$datohenter3 = "select DATE_FORMAT(datotid, '%Y.%m.%d') AS dato from gramorapport34 group by dato order by dato asc";
$hentdatoer = $db->query($datohenter3);

$periodedatoer = array();
for ($x = 1; $x <= $db->affected_rows; $x++) {
    $periodedatoer[] = $hentdatoer->fetch_assoc();
}

Then I want to match the values from this array with my next select query:

$rapportdatoer = "select fradato, tildato from gramorapportlogg WHERE  fradato IN('".$periodedatoer."') OR tildato IN('".$periodedatoer."')";
$rapportdatoeksist = $db->query($rapportdatoer);
if ( !$rapporteksist ) die('Database Error: '.$db->error);
    while($row = mysqli_fetch_array($rapportdatoeksist))
     {
        print_r($row);
     } 

The errors I am getting are:

Notice: Array to string conversion for the second select

Database Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' fradato IN('Array') OR tildato IN('Array')' at line 1

I'm not an expert in JOIN SELECT queries. This is using MariaDB 10.3.12 with PHP7.2

var_dump available at: https://www.lokalradio.no/rapport/gramo/datohenttest.php

Notice that $periodedatoer is an array of array. Each element inside has 1 key of dato (as you var_dump displays).

So use array-column to get the values and then implode as:

$rapportdato = implode("','", array_column($periodedatoer, "dato"));

Now you can use $rapportdato in your second query as:

$rapportdatoer = "select fradato, tildato from gramorapportlogg WHERE  fradato IN('" . $rapportdato . "') OR tildato IN('" . $rapportdato . "')";

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