Last active
June 19, 2018 21:33
-
-
Save brucenorton/63881fac229c76e757225472d62bfda7 to your computer and use it in GitHub Desktop.
stackoverlow 3 table join
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'mysqli_connection.php'; | |
ini_set('display_errors', 1); | |
ini_set('display_startup_errors', 1); | |
error_reporting(E_ALL); | |
//define table | |
$tbl = "photos"; | |
$joinsTbl = "joins"; | |
$catsTbl = "categories"; | |
//write query | |
$query = "SELECT $tbl.photoID, $tbl.photoSRC, $tbl.photoCredit, $joinsTbl.categoryID, | |
GROUP_CONCAT($catsTbl.photo_category SEPARATOR ',') AS categories | |
FROM $tbl | |
LEFT JOIN $joinsTbl | |
INNER JOIN $catsTbl | |
ON $joinsTbl.categoryID = $catsTbl.categoryID | |
ON $tbl.photoID = $joinsTbl.photoID | |
GROUP BY $tbl.photoID | |
LIMIT 100"; | |
//prepare statement, execute, store_result | |
if($displayStmt = $mysqli->prepare($query)){ | |
$displayStmt->execute(); | |
$displayStmt->store_result(); | |
$numrows = $displayStmt-> num_rows; | |
//echo("<br>results: $numrows"); | |
//echo($displayStmt->error); | |
} | |
$photosArray = []; | |
//bind results | |
$displayStmt->bind_result($photoID, $photoSRC, $photoCredit, $categoryID, $categories); | |
//fetch results | |
while($displayStmt->fetch()){ | |
$photosArray[] = ['photoID'=>$photoID, 'photoSRC'=>$photoSRC, 'photoCredit'=>$photoCredit, 'categoryID'=>$categoryID, 'categories'=>$categories, ]; | |
} | |
echo(json_encode($photosArray)); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment