Query syntax not correct - php

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:
$sql .= implode(",", $_SESSION['cart']) . ")";
The complete code looks like this:
$sql="SELECT * FROM component WHERE componentID IN (";
$sql .= implode(",", $_SESSION['cart']) . ")";
$query=mysql_query($sql) or die(mysql_error());
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:
$sql="SELECT * FROM component WHERE componentID IN (";
$sql .= implode(",", array_keys($_SESSION['cart'])) . ")";
$query=mysql_query($sql) or die(mysql_error());
array_keys() will extract the indexes of the array and ignore the values. If you want the values, stick to my first suggestion.

Try this one:
$sql = "SELECT * FROM component WHERE componentID IN (";
foreach($_SESSION['cart'] as $id => $value) {
$some_temp_array[] = $id;
}
$sql .= implode(',', $some_temp_array).")";

Related

SQL - syntax error

can you see what is wrong on this query? I have been watching it for really long time and I can't see it.
ERROR:
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 ''' at line 1
$sql="SELECT country_name FROM countries WHERE country_id IN (";
foreach($cartContentVsDatabase as $key => $val){
$sql.= $key['country_id'].",";
}
")";
Some issues:
You have a trailing comma in your country list,
countries should be quoted as strings,
you are accessing the values from the key instead of the value part of the array elements.
you have a dangling closing parenthesis, which does nothing.
You should not even inject country strings, as that makes your code vulnerable for code injection: use prepared statements.
Here is code you could use:
// first put the countries in an array
foreach($cartContentVsDatabase as $key => $val){
$countries[] = $val['country_id'];
}
// create a list of `?`: one for every country
$in = join(',', array_fill(0, count($countries), '?'));
// use that in the query
$sql="SELECT country_name FROM countries WHERE country_id IN ($in)";
// Prepare the statement (this is PDO syntax)
$statement = $pdo->prepare($select);
// Pass the countries as parameter values, and execute
$statement->execute($countries);
See this Q&A for more on prepared statements in the context of this in (...) clause.
try this,
change ")"; to $sql.= ")";
$array_count = count($cartContentVsDatabase);
$temp_count = 0;
$sql="SELECT country_name FROM countries WHERE country_id IN (";
foreach($cartContentVsDatabase as $key => $val){
$temp_count++;
if($array_count < $temp_count)
{
$sql.= $val['country_id'];
}
else
{
$sql.= $val['country_id'].",";
}
}
$sql.= ")";
You could make your life a lot easier by
$sql= "SELECT country_name FROM countries WHERE country_id IN (".implode(",",array_column($cartContentVsDatabase,"country_id")). ")";
You can (and probably should) use a prepared query e.g. like the one below:
$sql= "SELECT country_name FROM countries WHERE country_id IN (".implode(",",array_fill(0,count($cartContentVsDatabase),"?")). ")";
and then bind the contents of $cartContentVsDatabase when you execute.
In your code you are not concatenate ")"; properly at the end. you can also store data into array and than use implode() for comma separated values like:
Example:
<?php
$sql = "SELECT country_name FROM countries ";
$countries = array();
foreach($cartContentVsDatabase as $key => $val){
$countries[] = $val['country_id']; // store country id in your array
}
if(count($countries) > 0){
$countrylist = implode("','",$countries); // implode all country list with comma.
$sql .= "WHERE country_id IN ('$countrylist')";
}
echo $sql; // print your query.
?>
Still i don't know, $key['country_id'] is the correct one or not, i think this should be $val['country_id'].

PHP MVC SQL Syntax error

I am trying to implement a delete function in my MVC site. I have the following error
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 'id=27' at line 1
At the moment while I am trying to fix the error I have hard coded in the id 27, I have looked through the syntax for a simple row delete everywhere (eg. http://www.w3schools.com/php/php_mysql_delete.asp) but cant seem to find why I am getting the error?
deleteItem function
function deleteItem($parameters) {
$id = '27';
if ($this->model->deleteItem( $id )) {
$this->model->hasDeleteFailed = false;
$this->model->setDeleteItemConfirmation();
return (true);
}
else
$this->model->deleteItemError ( DELETE_ITEM_ERROR_STR );
}
SQL Code
public function deleteItem($id) {
$delId = $id;
$sqlQuery = "DELETE FROM items";
$sqlQuery .= "WHERE id=$delId;";
$result = $this->getDbManager () -> executeQuery ( $sqlQuery );
}
The code
$sqlQuery = "DELETE FROM items";
$sqlQuery .= "WHERE id=$delId;";
is the problem, since your SQL statement pretty much amounts to:
DELETE FROM itemsWHERE id=$delId
Notice that there is no space between the word "items" and the word "WHERE" in the SQL statement.
Also, you might as well refactor your code to
$sqlQuery = "DELETE FROM items WHERE id=$delId";
since there is no benefit to creating the SQL statement over two strings.
Also, you NEED to properly escape your SQL input parameters to prevent SQL Injection attacks. I don't know which PHP Framework you're using, so you'll need to look at how the framework does it. Take a look at the mysqli_real_escape_string function for this.
Also, you need to validate that the $id variable is actually an integer to prevent SQL Injection, since mysqli_real_escape_string is not entirely safe on its own. Use intval for this.
In your case you only need to make sure that $id is an integer value.
Thus, you should change your code to something like:
public function deleteItem($id) {
$delId = intval($id);
if ($delId <= 0)
return /* fail since ID is invalid */;
$sqlQuery = "DELETE FROM items WHERE id=$delId;";
$result = $this->getDbManager () -> executeQuery ( $sqlQuery );
}
This:
$sqlQuery = "DELETE FROM items";
$sqlQuery .= "WHERE id=$delId;";
Should be:
$sqlQuery = "DELETE FROM items "; // note the extra space at the end
$sqlQuery .= "WHERE id=$delId;";
Or:
$sqlQuery = "DELETE FROM items";
$sqlQuery .= " WHERE id=$delId;"; // note the extra space at the beggining
public function deleteItem($id) {
$delId = $id;
$sqlQuery = "DELETE FROM items";
$sqlQuery .= " WHERE id=$delId;";
$result = $this->getDbManager () -> executeQuery ( $sqlQuery );
}
Use space in $sqlQuery as I mention.

Insert data array in SQL after searching from another SQL table

I have an array $members that contains some ID(maximum 6 in number) from the table users. Using the following code, I loop through each index of $members, search for the details and store them in another array.
foreach($members as $key=>$value){
$res = mysql_query("SELECT id,name,email FROM users WHERE id='$value'");
if ($res === false) {
echo mysql_error();
die;
}
$row = mysql_fetch_assoc($res);
if($row['id'])
{
$members_name[]=$row['name'];//array for name
}
}
Now I want to insert the ID & names that are stored in the array into another TABLE register in the following format:
(The left side are the rows in my TABLE register)
mem_0_id-->$members[0]
mem_0_name-->$members_name[0]
mem_1_id-->$members[1]
mem_1_name-->$members_name[1]
mem_2_id-->$members[2]
mem_2_name-->$members_name[2]
mem_3_id-->$members[3]
mem_3_name-->$members_name[3]
mem_4_id-->$members[4]
mem_4_name-->$members_name[4]
How can I insert in this way? using just a single INSERT statement?
haven't tried this, but here is my answer anyway :)
$query = "INSERT INTO register(id, name) VALUES ($members[0], $members_name[0])";
for($i=1; $i<count($members); $i++)
{
$query .= ", ($members[$i], $members_name[$i])";
}
then try to execute the query..
Do you do anything else with the array, or are you just retrieving it from one table in order to insert it into another?
If so then you can do the whole thing like this.
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "insert into register (id, name) select id, name from users where id in ($memberIds)";
mysql_query($query); // this will select and insert in one go
If you do need to keep the array in memory, then it's still a good idea to get it all out at once
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "select id, name from users where id in ($memberIds)";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res)) {
$memberData[] = $row;
}
That's because running a query inside a loop is very bad for performance. Every time you run a query there is an overhead, so getting all the data at once means you pay this overhead once rather than multiple times.
Then you can build a statement to insert multiple rows:
$sql = "insert into register (id, name) values ";
$sql .= "(" . $memberData[0]['id'] . "," . $memberData[0]['name'] . ")";
for($i = 1; $i < count($memberData); $i++) {
$sql .= ",(" . $memberData[$i]['id'] . ",'" . $memberData[$i]['name'] . "')";
}
mysql_query($sql);
It's a bit nasty because of the commas and quotes but if I've done it correctly then if you do
echo $sql;
you should get something like
insert into register (id, name) values (1, 'john'), (2, 'jane'), (3, 'alice');
You can see that the first way, where you select and insert in one statment, is a lot nicer and easier so if you don't do anything else with the array then I highly recommend doing it that way.

Select from mysql table WHERE field='$array'?

If I have an array of say, some ID's of users. How could i do something like this:
$array = array(1,40,20,55,29,48);
$sql = "SELECT * FROM `myTable` WHERE `myField`='$array'";
Is there a simple way to do this, I thought about looping through array items and then building up one big "WHERE -- OR -- OR -- OR" statement but i thought that might be a bit slow for large arrays.
Use IN:
$sql = "SELECT * FROM `myTable` WHERE `myField` IN (1,40,20,55,29,48)";
you can use implode(",", $array) to get the list together from the array.
You want to use IN:
WHERE `myfield` IN (1,40,20,55,29,48)
Use implode to construct the string:
$sql = "SELECT * FROM `myTable` WHERE `myField` IN (" . implode(',', $array) . ")";

how to build a sql query using the content of a variable

I'm trying to build a query using php and mysql,
$query = "select * from products where product_name = '$item_name'";
this works when $item_name holds only one name, but $item_name is an array and based on the user's interaction can contain multiple names, how can I make the query to run for multiple name and get the resulted rows.
Thanks in advance
Here's how you could build a safe list of names for inserting into an IN clause...
if (is_array($names) && count($names))
{
$filter="('".implode("','" array_map('mysql_real_escape_string', $names))."')";
$sql="select * from products where product_name in $filter";
//go fetch the results
}
else
{
//input was empty or not an array - you might want to throw an
//an error, or show 'no results'
}
array_map returns the input array of names after running each name through mysql_real_escape_string to sanitize it. We implode that array to make a nice list to use with an IN clause.
You should always ensure any data, particularly coming directly from the client side, is properly escaped in a query to prevent SQL injection attacks.
$vals = implode(',',$item_name);
$query = "select * from products where product_name in (".$vals.");";
Give that a try.
$query = "select * from products where product_name in(";
foreach($item_name as $name)
{
$query .= "'" . $item_name . "', ";
}
$query = substr($query, 0, strlen$query) - 2);
$query .= ");";
First answer (by inkedmn) is really the best one though
foreach($item_name as $name) {
$query = "select * from products where product_name = '$name'";
//whatever you want to do with the query here
}
something like that ought to do it.
Based on inkedmn's response (which didn't quote the item names):
$query = 'select * from products where product_name in ("' . implode('", "', $item_name ) . '")';
Although you may be better with a fulltext search.
http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html

Categories