Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array in SQL Query? [duplicate]

Tags:

php

mysql

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

like image 990
njaknjak Avatar asked Mar 14 '11 07:03

njaknjak


People also ask

Can array contain duplicates?

To check if an array contains duplicates: Pass the array to the Set constructor and access the size property on the Set . Compare the size of the Set to the array's length. If the Set contains as many values as the array, then the array doesn't contain duplicates.

How can we prevent duplicate data in SQL query?

The SQL DISTINCT keyword, which we have already discussed is used in conjunction with the SELECT statement to eliminate all the duplicate records and by fetching only the unique records.


1 Answers

$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);
like image 199
Your Common Sense Avatar answered Oct 05 '22 18:10

Your Common Sense