MySQL query with and array [duplicate] - php

This question already has answers here:
Array in SQL Query? [duplicate]
(4 answers)
Closed 5 years ago.
I'm trying to create a tag function in my webpage and I'm using an array of tags to query the database.
array[tag1, tag2, tag3];
The tags are created in a field
what I'm trying to archive is something like
$query = "SELECT * FROM TABLE WHERE `Tags` = '$tag1' AND '$tag2' AND '$tag3'";
Except with an array, so
$query = "SELECT * FROM TABLE WHERE `Tags` = $array[]";
Thanks
$tag = $_POST['tag'];
$query = "SELECT * FROM ComicStripTags WHERE `Tag` = '$tag'";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
$ID[] = $row['ImageID'];
print_r ($ID);
}
BTW I want to use $ID[] to use in another query

Try using implode to convert array to string, and use "IN" operator instead of equal:
$query = "SELECT * FROM TABLE WHERE `Tags` in (". implode(", ",$array) .")";

Related

If remove WHERE from code it works other time it does not [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
if(isset($_GET['open'])){
$sub_id = $_GET['open'];
$sub_query = "SELECT * FROM `forum_sub` WHERE s_id = $sub_id";
$sub_run = mysqli_query($connection, $sub_query);
$sub_row = mysqli_fetch_array($sub_run);
$sub_name = $sub_row['title'];
}
/***
* Error starts here:
***/
$topic_query = "SELECT * FROM `forum_topic` WHERE categories = $sub_name";
$topic_run = mysqli_query($connection, $topic_query);
/***
* Note also here:
***/
while($topic_row = mysqli_fetch_array($topic_run)){
$p_id = $topic_row['id'];
$p_title = $topic_row['subject'];
$p_msg =$topic_row['msg'];
$p_date = $topic_row['date'];
$p_username = $topic_row['u_name'];
$p_view = $topic_row['view'];
}
When I Remove WHERE then it is okay otherwise it gives error
Please help me
I tried every way but it just not happening. if I remove WHERE tag then it is happening properly
forum_topic structure
use this
$sub_query = "SELECT * FROM `forum_sub` WHERE s_id =". $sub_id;
Your variables placed inside of the if statement are undefined when outside of the if statement.
Try
if(isset($_GET['open'])){
$sub_id = $_GET['open'];
$sub_query = "SELECT * FROM `forum_sub` WHERE s_id = $sub_id";
$sub_run = mysqli_query($connection, $sub_query);
$sub_row = mysqli_fetch_array($sub_run);
$sub_name = $sub_row['title'];
$topic_query = "SELECT * FROM `forum_topic` WHERE categories = $sub_name";
$topic_run = mysqli_query($connection, $topic_query);
while($topic_row = mysqli_fetch_array($topic_run)){
$p_id = $topic_row['id'];
$p_title = $topic_row['subject'];
$p_msg =$topic_row['msg'];
$p_date = $topic_row['date'];
$p_username = $topic_row['u_name'];
$p_view = $topic_row['view'];
}
}

How to use PDO prepared statements with IN clause? [duplicate]

This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 1 year ago.
I stored some data in a field inside MySQL in this format: 1,5,9,4
I named this field related. Now I want to use this field inside an IN clause with PDO. I stored that field contents in $related variabe. This is my next codes:
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (?) LIMIT 4";
$q = $db->prepare($sql);
$q->execute(array($related));
echo $q->rowCount();
But after executing this code, I can fetch only one record whereas I have to fetch 4 records (1,5,9,4). What did I do wrong?
using named place holders
$values = array(":val1"=>"value1", ":val2"=>"value2", ":val2"=>"value3");
$statement = 'SELECT * FROM <table> WHERE `column` in(:'.implode(', :',array_keys($values)).')';
using ??
$values = array("value1", "value2", "value3");
$statement = 'SELECT * FROM <table> WHERE `column` in('.trim(str_repeat(', ?', count($values)), ', ').')';
You need as many ? placeholders as your "IN" values.
So:
$related = array(1,2,3); // your "IN" values
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (";
$questionmarks = "";
for($i=0;$i<count($related);$i++)
{
$questionmarks .= "?,";
}
$sql .= trim($questionmarks,",");
$sql .= ") LIMIT 3;";
// echo $sql; // outputs: SELECT id,title,pic1 FROM tbl_products WHERE id IN (?,?,?) LIMIT 3;
$q = $db->prepare($sql);
$q->execute($related); // edited this line no need to array($related), since $related is already an array
echo $q->rowCount();
https://3v4l.org/No4h1
(also if you want 4 records returned get rid of the LIMIT 3)
More elegantly you can use str_repeat to append your placeholders like this:
$related = array(1,2,3); // your "IN" values
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (";
$sql .= trim(str_repeat("?,",count($related)),",");
$sql .= ") LIMIT 3;";
// echo $sql; // outputs: SELECT id,title,pic1 FROM tbl_products WHERE id IN (?,?,?) LIMIT 3;
$q = $db->prepare($sql);
$q->execute($related); // edited this line no need to array($related), since $related is already an array
echo $q->rowCount();
https://3v4l.org/qot2k
Also, by reading again your question i can guess that your $related variable is just a string with value comma-separated numbers like 1,40,6,99. If that's the case you need to make it an array. do: $related = explode($related,","); to make it an array of numbers. Then in your execute method pass $related as-is.

How optimize while in while code? [duplicate]

This question already has an answer here:
Optimize while and SQL in foreach
(1 answer)
Closed 8 years ago.
My code is :
$text = '12-10-4-32-45-name-sara-x-y-86';
$array = explode('-',$text);
foreach($array as $value) {
$sql = mysql_query("SELECT * FROM `table` WHERE `pid`='$value' ORDER BY `id` LIMIT 3");
while($row = mysql_fetch_array($sql)) {
echo $row['title'];
echo '';
}
echo '';
}
This code work full but if in $text use 150 variable , server down !
How optimize this code for most variable ?!
Thx
If you need all of them as ids (which includes a string which is weird). Consider this example:
$text = '12-10-4-32-45-name-sara-x-y-86';
$text = array_unique(explode('-', $text)); // just in case there are duplicate ids
$statement = 'SELECT * FROM `table` WHERE `pid` IN("'.implode('", "', $text).'") ORDER BY `id` LIMIT 3';
// should be like this
// SELECT * FROM `table` WHERE `pid` IN("12", "10", "4", "32", "45", "name", "sara", "x", "y", "86") ORDER BY `id` LIMIT 3
// then just continue on your mysql_query
$sql = mysql_query($statement);
while($row = mysql_fetch_assoc($sql)) {
// print your values or whatever it is you need to do
// echo $row['title'];
}
Note: You don't need to query each value, that would be a total waste of resources. Imagine your text has (as you said) 150 numbers. Try to use the IN() of mysql so that it just make a single trip of query.

Save sql result to variable using php [duplicate]

This question already has answers here:
Get the single value of a sql result set
(3 answers)
Closed 9 years ago.
I have this query:
$result = "SELECT MAX(N) as maxid FROM (
SELECT SUBSTRING(id_f, 2,len(id_f) -1) as N
From formas WHERE id_f LIKE '%D%'
) t" ;
$res = odbc_exec($connection, $result) or die(odbc_error());
Now, if i put the query in SQL SERVER i get the correct result.
What i need is to save the maxid as a variable.. how to do it?
Thanks
What you need is the function odbc_fetch_array.
$result = "SELECT MAX(N) as maxid FROM (
SELECT SUBSTRING(id_f, 2,len(id_f) -1) as N
From formas WHERE id_f LIKE '%D%'
) t" ;
$res = odbc_exec($connection, $result) or die(odbc_error());
$info = odbc_fetch_array($res);
$content[] = $info;
$maxN = $content[0]
For a multiple rows query, you need to encapsulate the function in a while loop :
while($row = odbc_fetch_array($res))
{
print_r($row);
}

Array in SQL Query? [duplicate]

This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 8 years ago.
i have a problem making a SQL Query with an array in my WHERE clause.
For example:
My Array:
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
My MySQL Statement:
SELECT * FROM myTable WHERE title='".$myarray[]."'
Is there any way to realize that?
I solved it myself like this:
for(...) {
$where = $where." title='".$myarray[$count]."' OR ";
}
$where = substr($where , 0, -3);
.....
SELECT * FROM myTable WHERE ".$where."
But if i had thousands of entries in my array, the SQL Statement would be too big and slow, right?
Thanks
You can use mysql's IN-function
EDIT: As amosrevira said, you need to escape you strings in the array.
$myarray[1] = "'hi'";
$myarray[2] = "'there'";
$myarray[3] = "'everybody'";
$newarray = implode(", ", $myarray); //makes format 'hi', 'there', 'everybody'
SELECT * FROM myTable WHERE title IN ($newarray);
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
//every quoted string should be escaped according to SQL rules
foreach($myarray as $key => $val) {
$myarray[$key] = mysql_real_escape_string($val);
}
$in_str = "'".implode("', '", $myarray)."'"; //makes format 'hi', 'there', 'everybody'
SELECT * FROM myTable WHERE title IN ($in_str);
You can try use of IN in your WHERE clause,
SELECT * FROM myTable WHERE title IN ('hi', 'there', 'everybody');
or
SELECT * FROM myTable WHERE title IN ('.implode(',', $myarray).');
You can us the IN operator. You want it to look like:
title IN ('hi', 'there', 'everybody')
So you'd do something like:
$sql = "SELECT * FROM myTable WHERE title IN '" . implode("','", $myarray) . "';"
Note that you need to filter your array for SQL injection issues first.

Categories