I have an SQL query which displays 2 rows retrieved but when I echo the field name nothing is retrieved. Anyone know what I am doing wrong?
$sql = 'SELECT *
FROM tag_map
LEFT JOIN tags2 ON tags2.tag_id = tag_map.tag_id
LEFT JOIN video ON video.vid_id = tag_map.vid_id
WHERE tag_map.vid_id=?';
$stmt_tags = $conn->prepare($sql);
$result=$stmt_tags->execute(array($vid_id));
echo $tag_count=$stmt_tags->rowCount(); //shows 2
$tags = array();
while ($row = $stmt_tags->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'];
}
EDIT: Var_dump using suggested query
SELECT tag_map.*, tags2.name AS tag_name
FROM tag_map
LEFT JOIN tags2 ON tags2.tag_id = tag_map.tag_id
LEFT JOIN video ON video.vid_id = tag_map.vid_id
WHERE tag_map.vid_id=?
array(4) { ["id"]=> string(4) "1234" ["vid_id"]=> string(32) "8364a8e463052e215a5dc174c92a2f18" ["tag_id"]=> string(32) "4c71a73d001dd9c09c7d9d95907bf1fe" ["tag_name"]=> NULL } array(4) { ["id"]=> string(3) "123" ["vid_id"]=> string(32) "8364a8e463052e215a5dc174c92a2f18" ["tag_id"]=> string(32) "57bb5dd83dc84e7115387886e328b04b" ["tag_name"]=> NULL }
You should be specific in your
SELECTclause, particularly when joining other tables.For example
Notice how I’ve used an alias for
tags2.nameto avoid a column name conflict withtag_map.name.I’m only guessing here but I’d say you have a
namecolumn in one of your left-joined tables that’s overridingtag_map.name.Update
In light of the extra information, I’d have to say it’s solely due to your left-joins. The records where
tags2.nameis showing NULL simply do not have related fields intag_mapfor thevid_idin question.If you only want to show records where there is a relation between
tag_mapandtags2, useINNER JOINDemo here – http://sqlize.com/UL1M80DT0c