简体   繁体   中英

Get data from mysql table and use them in "IN" in sql query (PHP)

I have this php script to get data from database:

$sev = mysqli_query($conn, "SELECT DISTINCT(SRV) FROM customers WHERE custValue NOT REGEXP '^$' AND id=345532 AND custValue IN ("A+", "B", "C") ");

When I try the sql query on database server, it correctly returns following data:

________
|  SRV  |
---------
|   A+  |
|   B   |
|   C   |
|   XN  |
|   BN  |
|   DS  |
|   XA  |
---------

then I try to implode..

$custSev = mysqli_fetch_array($sev);
$csImp = "'" . implode("','", $custSev) . "'";

and as the last step I use $csImp in another query

... AND severity IN ($csImp) AND ...

but when I check it on database server, it receives following sql query:

... AND severity IN ('A+','A+') AND ...

I have no idea why there is the first value twice and no other value. It should be

... AND severity IN ('A+','A+','C','XN','BN','DS','XA') AND ...

And again, when I execute this query on DB server, it's working correctly. I'm struggling with this for whole day and tried many combinations without effect. I'm still beginner in PHP. Thank you

I've tried to change $sev to $sev = array('A+','A+','C','XN','BN','DS','XA'); but then in the sql query is "...IN ('')..."

I've tried the following:

$row = $sev -> fetch_assoc();
$show = printf ("%s (%s)\n", $row["SRV"]);

and implode the $show variable and use it in the query, but the "...severity IN ('')..." was empty like in previous case.

The data you have retrieved here is in several rows:

________
|  SRV  |
---------
|   A+  |
|   B   |
|   C   |
|   XN  |
|   BN  |
|   DS  |
|   XA  |
---------

But this code only retrieves the first row:

$custSev = mysqli_fetch_array($sev);
$csImp = "'" . implode("','", $custSev) . "'";

Unless you specify otherwise, you'll retrieve an array index by column name and by a numeric index, hence two entries, which when imploded gives:

... AND severity IN ('A+','A+') AND ...

As has been pointed out in the comments, you could just use a subquery to do this, but to answer the problem you've posted:

$severityList = [];
while ($row = mysqli_fetch_array($sev)) {
    $severityList[] = $row['SRV'];

}
$csImp = "'" . implode("','", $severityList) . "'";

**Disclaimer - I haven't tested this. Apologies for any typos!

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