Getting this error, dont know what is causing it. checked other answers for this error but cannot get it to work. Any help is appreciated
<?php
session_start();
include ('includes/header.html');
if ( isset($_GET['id'])) $id = $_GET['id'];
require ('../connect_db.php');
$q = "SELECT *
FROM books_for_sale
WHERE book_id = $id";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1 )
{$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
if (isset($_SESSION['cart'][$id]))
{
$_SESSION['cart'][$id]['quantity']++;
echo '<p>Another' .$row["book_name"]. 'has been added</p>';
}
else
{
$_SESSION['cart'][$id]=
array ( 'quantity' => 1, 'price' => $row['item_price']);
echo '<p>1 '.$row["item_name"]. 'has been added to your order</p>';
}
}
mysqli_close($dbc);
include('includes/footer.html');
?>
The reason for the error is that '$id' is not in single quotes.
Also, you're taking values from form/get submissions and putting them directly into your mysql query without any server side checking that the data is valid. This is very insecure as it would allow an attacker to inject code into the mysql query.
What you need to be doing is using 'prepared statements' so that you can pre-define server side what type of values can be used in the mysql query. That way if an evil form value gets submitted php will be able to detect it and return an error.
I think your select query is broken.
I recommend escaping your super global ($_GET['id']) to filter_input(INPUT_GET, 'id', FILTER_SANITIZE_SPECIAL_CHARS);
. Also do you have a default value for $id? It could be the reason why it breaks.
Your query could be
$q = "SELECT * FROM books_for_sale ".(isset($id) ? "WHERE book_id = ".(int)$id : "");