Jimmy Jimmy - 7 months ago 13
SQL Question

MYSQL tables with same column name

Fetching and print results from multiple tables that have same column name. Here's my query: I am trying to fetch the column

salt
from
login
and
cookie
table.

SELECT login.salt
, cookie.salt
FROM login
, cookie
WHERE login.user_id
AND cookie.user_id = :user_id`

login
+---------------------------+
| user_id | salt |
+---------+-----------------+
| 1 | fromLogin |
| 2 | fromLogin |

cookie
+---------------------------+
| user_id | salt |
+---------+-----------------+
| 1 | fromCookie |
| 2 | fromCookie |


The result was:

Array ( [salt] => fromCookie )


How can i print both result out?

PHP


$user_id = 1;

$sql = "SELECT login.salt, cookie.salt FROM login, cookie WHERE login.user_id AND cookie.user_id = :user_id";

$params = array(
'user_id' => $user_id
);

$stmt = $db->justConnect()->prepare($sql);
$stmt->execute($params);
$result = $stmt->fetch(PDO::FETCH_ASSOC);

print_r($result);

Answer

Use alias with query.

$user_id = 1;

$sql = "SELECT login.salt as loginSalt, cookie.salt as cookieSalt FROM login, cookie WHERE login.user_id AND cookie.user_id = :user_id";

$params = array(
        'user_id' => $user_id
        );

$stmt = $db->justConnect()->prepare($sql);
$stmt->execute($params);
$result = $stmt->fetch(PDO::FETCH_ASSOC);

print_r($result);