简体   繁体   中英

php return 1 data set from 2 mysql queries

Currently I'm getting a single row from a single table and returning that to be processed by JS:

$sql = "SELECT * FROM labs WHERE lab_id = $lab_id";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
// send the data encoded as JSON
echo json_encode($row);

But now I need to add some data from another table. The "labs" table has a "lab_model_id" column which is an int. I need to use that "lab_model_id" to get "lab_model_name" from "lab_models".

1) How do I pull out the "lab_model_id" in my php to perform the second query?

2) Can I add the second result to the first before returning?

Try using JOIN..

$sql = "SELECT labs.*,`lab_models`.`lab_model_name`
        FROM labs
        LEFT JOIN lab_models
        ON lab_models.lab_model_id = labs.lab_model_id
        WHERE lab_id = $lab_id";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
// send the data encoded as JSON
echo json_encode($row);

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