Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ORDER BY before second request

I have two tables. One is a list of the dishes a user wants to cook associated with their level of priority. The second one associate a dish with its recipe.

I would like to do the following : Print all the dishes the user wants to cook with their recipe ordered by the priority level of each dish.

I tried doing the following :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        $req = $pdo->prepare('SELECT dish, priority FROM dish_task WHERE (username = :username) ORDER BY priority');
    $req->execute(['username' => $username]);
    $dish = $req->fetchAll();

    if ($dish != null) {

        //get right format -> (dish_1, ..., dish_n)
        $listDish = ""; 

        foreach ($dish as $d) {

            $listDish = $listDish . "'". strval($f['dish']) . "'" . ",";

        }

        $listDish = substr($listDish, 0, -1);

        $req = $pdo->prepare('SELECT dish, recipe FROM dish_data WHERE dish IN (' . $listDish . ')');
        $req->execute();

        $taskList = $req->fetchAll();

        echo json_encode($taskList);

The problem is that doing the second request seems to cancel the ORDER BY I did previously… So I don’t know how I can manage to get what I want well ordered ?

>Solution :

Use a single query that joins the two tables.

$req = $pdo->prepare('
    SELECT dt.dish, dd.recipe
    FROM dish_task AS dt
    JOIN dish_data AS dd ON dt.dish = dd.dish
    WHERE (dt.username = :username) 
    ORDER BY dt.priority');
$req->execute(['username' => $username]);
$taskList = $req->fetchAll();
echo json_encode($taskList);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading