简体   繁体   中英

mysql - Select all from one table and one column form another where $var is found

Ooooookay. I have two tables client and users. Both have AUTO_INCREMENT id but client table has credid-column whis is foreign key and references to users table's id.

I want to prepare a PHP PDO statement that fetches all columns from client-table and only username-column from users-table where client table's column credid = :var and user table's column id = :var

So far I have something like this and it is not working

$userid = $_SESSION['id']; //echoes a number
    $STH = $DBH->prepare("SELECT * FROM client WHERE credid = :id AND username FROM users
    WHERE id = :id");
    $credentials = array(
        ':id' => $userid
    );
    $STH->execute($credentials);

Then like this

    if ($STH->rowCount() > 0) {
        $result = $STH->fetch(PDO::FETCH_ASSOC);
        echo $result['columnfoo'];
        echo $result['anothercolumn'];
        echo etc.
        .
        .
        .

    }

This return errors about sql syntax....

I also tried something like this:

    SELECT client.*,users.username FROM client,users WHERE client.credid =users.id = :id

Returns no errors but not any data either... How should I construct my prepared query?

You need to use a join :

SELECT c.*, u.username
FROM   client c
JOIN   users u ON u.id = c.credid
WHERE  credid = :id

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