I'm having a problem trying to get the results value of my first SQL statement so I can then use in within my second statement.
My first statement is this:
$query = "SELECT restaurantid FROM restaurant WHERE username = '$_SESSION[username]'";
$result=mysql_query($query);
if(!$result)
{
echo "Error: " . mysql_error() . "Query: " . $query;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['restaurantid'];
}
mysql_free_result($result);
From an inspector console I am using on my browser this statement returns a '1' when launched which is the variable I'm looking for.
Directly underneath my last line (mysql_free_result....) I being my second query like so:
$query = "INSERT INTO deal (dname, description, restaurantid) VALUES ('$name', '$desc', '$result')";
$add = mysql_query($query);
$num = mysql_numrows($add);
if($num != 0) {
echo "true";
} else {
echo "Error: " . mysql_error() . "Query: " . $query;
}
However my problem lies that whenever I try and execute this code my second statement does not appear to be picking up on the previous result value needed from the first query. Just hoping someone could shed some light on the situation for me. I am new to coding and I almost have this correct so all help and advice would be greatly appreciated! Thanks :)
First off, you shouldn't use Mysql since it has been deprecated and is vulnerable to SQL injections, use Mysqli instead.
$restaurantId = $row['restaurantid'];
Though by using Mysql, the query should look like this "INSERT INTO deal (dname, description, restaurantid) VALUES ('$name', '$desc', '$restaurantId')"
and by using Mysqli it should look like this:
$stmt = $mysqli -> prepare("INSERT INTO deal (dname, description, restaurantid) VALUES (?,?,?)"
$stmt -> bind_param('ssi', $name, $desc, $restaurantId);
$stmt -> execute();