How do I create a dynamic SQL string using Parameters? - php

I'm stuck with this portion where I know there is definitely a way to do this dynamically, but I just don't know how.
How do I, upon receiving a search query, and knowing how many arrays are in the search query, dynamically creates a SQL string?
Below are parts of the code shown. Any help is appreciated, thanks! =)
if ($arraycount ==2){
$searchSQL = $db->query("SELECT * FROM table WHERE field1 IN (SELECT field2 FROM $table WHERE field3 IN ('$array[0]','$array[1]'));");
}
else if ($arraycount ==3){
$searchSQL = $db->query("SELECT * FROM table WHERE field1 IN (SELECT field2 FROM $table WHERE field3 IN ('$array[0]','$array[1]','$array[2]'));");
}

You can use implode to concatenate values of an array.
$sql = "SELECT * FROM table WHERE field1
(SELECT field2 FROM $table
WHERE field3 IN ('".implode("','", $array)."')";
$searchSQL = $db->query($sql);
Here is Codepad demo.

All credit to #peterm, but with extra security measure (if you use MySQL)
... implode("','", array_map("mysql_real_escape_string", $array))

Related

Select statement with where clause Like in array

I know how to perform an SQL LIKE % query for a single value like so:
$sql = "SELECT * FROM Farmers WHERE Available_products LIKE ('%Bananas%')";
but how do I do this if the search terms for my LIKE comes from an array? For example, let's say we have an array like this:
$_POST['Products']="Cacaos,Bananas";
$array=implode(',', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE Available_products LIKE ('%$array%')";
I want to get all the records in database that the column Available_Products contains Cacaos or Bananas or Both
Convert the array to a regular expression and use REGEX instead of LIKE
$_POST['Products'] = array('Cacaos', 'Bananas');
$regex = implode('|', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE Available_products REGEX :regex";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':regex', $regex);
$stmt->execute();
You can try with the help of REGEXP .
$_POST['Products']="Cacaos,Bananas";
$array=implode('|', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE
Available_products REGEXP". $array; 
You can also do something like :
// Populating join table.
CREATE TABLE temp_table_myArray (myArray nvarchar(255));
INSERT INTO temp_table_myArray (myArray) VALUES ('Cacaos');
INSERT INTO temp_table_myArray (myArray) VALUES ('Bananas');
// Query using the join table.
SELECT F.*
FROM Farmers AS F
INNER JOIN temp_table_myArray AS T ON (F.Available_products LIKE(CONCAT('%',T.myArray,'%')));
But I think there is a better PHP way to solve your problem...

Select From table results that don't equal to $var?

How do I make it pick all results that are not equal to the $var , here's my code.
$opti=mysql_query("SELECT * FROM table1 WHERE imageid=$image_id");
while ($vari = mysql_fetch_array($opti)) {
$var = $vari['tagid'];
$options=mysql_query("SELECT * FROM table WHERE id!=$var");
while ($taghe1 = mysql_fetch_array($options)) {
$tagname = $taghe1['name'];
echo "".$tagname.", ";
} }
Try:
$options=mysql_query("SELECT * FROM table WHERE id<>{$var}");
You can probably see from the answer you accepted that adding the quotes solved your problem. Another way to do this is to just use one query. I will show an example using mysqli instead of the deprecated mysql, but the same query should work in mysql if you must use it. I added a couple of other suggestions that aren't really addressing your question, but make me feel better about my answer.
// Please be sure to escape $image_id before using it like this
$unused_tags = mysqli_query($db, "SELECT `name` FROM `table` AS t
LEFT JOIN (SELECT tagid FROM table1 WHERE imageid=$image_id) AS t1
ON t.id = t1.tagid WHERE t1.tagid IS NULL;");
while ($tag = mysqli_fetch_array($unused_tags)) {
$tags[] = htmlspecialchars($tag['name']); // escape your output
}
echo implode(", ", $tags); // doing it this way eliminates the trailing comma
You could use this:
$options=mysql_query("SELECT * FROM table WHERE id not in ('$var')");
You could have multiple values here, e.g.
$options=mysql_query("SELECT * FROM table WHERE id not in ('$var1', '$var2', '$var3')");

Use an array inside a query string

Im trying to pass an array that I already found by a query into another query. For example:
$first_query = "SELECT id FROM from Table WHERE user = '{$_SESSION['id'}'";
$result = mysql_query($first_query,$connection);
$ids = mysql_fetch_array($result);
This is where it gets tricky for me. I want to pass $ids into the next query.
$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id = '{$id_implode}';
The second query doesnt seem to be working. Any help is greatly appreciated!
your second query's syntax is wrong. Once evaluated it should read
select * from Table2 where id in (1,2,3)
ditch the curly braces and change the = to in. Don't use OR - that's a dumb way of ignoring good sql functionality
EDIT: Teneff's comment makes a very good point - why are you approaching the problem in this way? If there is a relationship between the tables they can be joined and all the data you want can be retrieved in a single query. If for some reason you can't / won't join the tables you could at least try a sub-query
select * from table2 where id in (select id from table where user = $_SESSION['id']);
To use a where statement with multiple entries to match on, use in ().
$id_implode = "'".implode("', '", $ids)."'"
$second_query = "SELECT * FROM Table2 WHERE id in ({$id_implode});
I think you should use IN
$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id IN '({$id_implode})';
This assumes that $ids is made of int of course, otherwise you have to enclose eache entry in quotes. that means
IN (6,7,8,9)//this doesn't need quotes
IN ('lemon', 'orange')//needs quotes
try to use the IN syntax:
$id_implode = implode("', '", $ids);
$second_query = "SELECT * FROM Table2 WHERE id in ('{$id_implode}');

How do you query using an "IN" WHERE clause with Zend_Db_Adapter_Mysqli::fetchAll()?

I'm having a strange problem with Zend_Db_Adapter_Mysqli. I need to query multiple items by ID from my database, so I have the following SQL,
SELECT * FROM mytable WHERE id IN (1,2,3)
This query works fine.
I then try and do this programatically with Zend_Db_Adapter_Mysqli,
$sql = 'SELECT * FROM mytable WHERE id IN (?)';
$ids = array(1,2,3);
$result = $adapter->fetchAll($sql, implode(',', $ids));
The problem is for the above PHP I only get back 1 result instead of the expected 3. I've tried just passing the $ids instead of using implode(), but I just get an error.
What am I doing wrong?
I'm not sure if it helps, but here's an answer on how to do it using Zend_Db_Select: How to create WHERE IN clause with Zend_Db_Select
EDIT:
Ok, if it really doesn't work, and you were planning on using a string anyway, can't you just do this:
$ids = array(1,2,3);
$sql = sprintf('SELECT * FROM mytable WHERE id IN (%s)', implode(',' $ids));
$result = $adapter->fetchAll($sql);
:)
Or, even more wonderful:
$ids = array(1,2,3);
$sql = sprintf('SELECT * FROM mytable WHERE id IN (%s)', implode(',' array_fill('?', count($ids)));
$result = $adapter->fetchAll($sql, $ids);
However, I'm not sure fetchAll would accept this.
Not so easy. See here:
http://forums.mysql.com/read.php?45,64588,66133#msg-66133
The fact that you get only one result is thanks to MySQL interpreting the string '1,2,3' as number 1. You will explicitly have to add three question marks to the query:
$ids = array(1,2,3);
$sql = 'SELECT * FROM mytable WHERE id IN (?, ?, ?)';
$result = $adapter->fetchAll($sql, $ids);
You can write a function that will transform $ids to the right number of question marks.
See this question/answer for a way to use the IN clause with a parameterized statement.
I have an array of integers, how do I use each one in a mysql query (in php)?

Unknown column 'xyz' in 'where clause'

I created a user defined sql query that doesn't work. Users are supposed to be able to enter search strings in an input field, submit then see the results of their search but everytime I enter a search for something that I know is in the database I get the unknown column "x" in "where clause" error message.
Would you please help me fix the problem? Here's the code that i wrote for it so far...
...
mysql_select_db("mydb", $c);
$search = $_POST['search'];
$rslt = mysql_query("SELECT * FROM mytable
WHERE 'mycolumn' RLIKE $search");
while($row = mysql_fetch_array($rslt))
{
echo $row['myrow'];
echo "<br />";
}
if (!$row)
{
die('uh oh: ' . mysql_error());
}
?>
Change the code to this:
1) Convert quotes to backticks around column name.
2) Surround $search with single qoutes to make it a string.
$rslt = mysql_query("SELECT * FROM mytable WHERE `mycolumn` RLIKE '{$search}'");
This helps for sure
just change the variable $search to be read as a string i.e $search
so it will be like this
$rslt = mysql_query("SELECT * FROM mytable WHERE mycolumn RLIKE '$search'");
I would like to add a few about security and performance.
It is unsafe to put user input (any GET, POST or cookie data) directly into the SQL query. This is a serious security issue called SQL injection. To avoid it, use mysql_real_escape_string() function.
Also, SELECT * FROM mytable ... is not a good practice. It is recommended to explicitly list all the columns needed even if they all are:
SELECT col1, col2, col3, col4, col5 FROM mytable ...

Categories