I’m currently making a cart and i’m having trouble with my SQL query below:
$sql="SELECT * FROM component WHERE componentID IN (";
foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).")";
$query=mysql_query($sql) or die(mysql_error());
So i’m trying to check the SESSION items with my database items using a select and a foreach. The code loops through the SESSION and adds the componentID to the SELECT, which is then taken into the substr function to remove the last comma (e.g. removing ‘001,002*,*’. I’m sure the syntax is right, however I keep getting a syntax error which is:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ‘00004,00007)’ at line 1
Can anyone see what i’m doing wrong here?
I think this line is your problem:
You could also simplify the process of making the comma separated set of id’s as ccKep suggests:
The complete code looks like this:
This will get the values from $_SESSION[‘cart’] – if you really want the indexes of the array, as you first coded it, there’s this option:
array_keys() will extract the indexes of the array and ignore the values. If you want the values, stick to my first suggestion.