简体   繁体   中英

INNER JOIN and WHERE clause with session

I am trying to join three tables and also bring in a tutID session so it carries it through from the previous page. The commented out SQL statement is needed to be in the SQL statement.

<?php
session_start(); 
if (!isset($_GET['tutID']) || !is_numeric($_GET['tutID']))
{
header('Location: ./allTutorials.php');
}
else
{

// Include databse connection file
include('./inc/connection.inc.php');

// Get record details
connect();

$tutID = $_GET['tutID'];
/*$sql =    "SELECT * FROM tutorials WHERE tutID = '$tutID' ";*/
$sql = "SELECT * FROM tutorials INNER JOIN tutorialimages ON tutorials.tutID = tutorialimages.tutID INNER JOIN images ON images.imageID = tutorialimages.imageID" ;


$result = @mysql_query($sql) or die('Unable to run query');
$record = mysql_fetch_object($result);

mysql_close();  
?>

Add WHERE in your JOIN query -

$sql = "SELECT * FROM tutorials 
        INNER JOIN tutorialimages ON tutorials.tutID = tutorialimages.tutID
        INNER JOIN images ON images.imageID = tutorialimages.imageID 
        WHERE tutorials.tutID = " . ((int) $tutID)
;

You'll notice I've re-cast the tutorial ID to an integer. This is a safety measure to prevent a malicious user from injecting SQL into your query. Whilst this is safe, it would be better to switch to a database engine that offers parameterisation , which makes this easier.

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