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

老子叫甜甜 提交于 2019-12-08 02:11:48

问题


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?


回答1:


You need to use a join:

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


来源:https://stackoverflow.com/questions/25721054/mysql-select-all-from-one-table-and-one-column-form-another-where-var-is-foun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!