简体   繁体   中英

How do I SELECT these two tables using single PDO query

I have two tables, which I want to SELECT using a single PDO query and positional placeholders.

I've been going through similar questions here to find a solution, but none seems to match the issues I'm having.

The following code is the section of my script:

// query users table to retrieve its contents   
if (isset($_SESSION["user_id"]["0"])) {
    // select a particular user by user_id
    $user_id = isset($_POST["user_id"]) ? $_POST["user_id"] : '';

    $stmt = $pdo->prepare("SELECT * FROM users WHERE user_id=?", $_SESSION["user_id"]["0"]);
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(); # get user data
}

// query courses table to retrieve its contents            
$cid = $_POST["cid"] ?? NULL;
if (is_null($cid)) {
    $stmt = $pdo->query("SELECT * FROM courses");
} else {
    $stmt = $pdo->prepare("SELECT * FROM courses WHERE cid = ?");
    $stmt->execute([$cid]);
}

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<option value="">' . "Select a course to proceed" . '</option>';
foreach ($results as $row) {
    echo '<option value=" ' . $row["cid"] . ' ">' . $row["c_name"] . '</option>';
}

Apart from echoing $row["cid"] (course ID) and $row["c_name"] (course name) from the courses table, I'm also echoing the following from the same courses table: $row["code"] , $row["duration" ], $row["start"]

In the users table, I have the logged in user's "user_id" , "firstname" , "lastname" , "username" , "email" , which I also want to include in the above foreach loop. That means the user must be logged in.

SELECT p. p_id, p.cus_id, p.p_name, c1.name1, c2.name2  

FROM product AS p  

LEFT JOIN customer1 AS c1  

ON p.cus_id=c1.cus_id  

LEFT JOIN customer2 AS c2  

ON p.cus_id = c2.cus_id 

You can achieve this by doing this. There are 2-3 ways more but this is simplest.

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