How to use an array to query

Asked by At

Is there any way I can use the array from $query and use it in another query like the $query2 below? It works but it only returns the first data of the array...

Already tried these links already but none of them worked in my case Array in SQL Query?

How to query a database with an array? WHERE = 'array()'

$query = mysqli_query($db, "SELECT * FROM patient_details WHERE discharged_date >= '2019-03-01' AND discharged_date < '2019-03-30'");
    while ($row = mysqli_fetch_array($query)){
        $result = $row['hosp_patient_no'];
        $query2 = mysqli_query($db, "SELECT deficiencies_id FROM deficiency_patient_details WHERE hosp_patient_no = '$result'");

}

1 Answers

0
Pritam Jinal On

you are using mysqli_fetch_array which will "Fetches a result row as an associative, a numeric array, or both", but your requirement says it otherwise so you should use mysqli_fetch_all which "Fetches all result rows as an associative array, a numeric array, or both".

so your syntax should look like this

$query = mysqli_query($db, "SELECT * FROM patient_details WHERE discharged_date >= '2019-03-01' AND discharged_date < '2019-03-30'");
while ($row = mysqli_fetch_all($query)){
    $result = $row['hosp_patient_no'];
    $query2 = mysqli_query($db, "SELECT deficiencies_id FROM deficiency_patient_details WHERE hosp_patient_no = '$result'");

}

infact i would suggest you to do this in a single query using subquery.