-3

I have statements like this :

$q1="SELECT * FROM indexing WHERE keywords IN '(".implode(' , ' , $words). ")";
$result = mysqli_query($con,$q1) ;

I need to get details from indexing table based on the values in the variable $words.
But now its always showing the returned number of rows as zero.
How to add the quotes properly in the sql statement in order to get the correct result.

Mohd Dhiyaulhaq
  • 89
  • 1
  • 14

3 Answers3

1

If you echo (or vardump or printf) q1, for debugging, you would see the actual SQL text being sent to the server.

There's a few problems here. There's a single quote before the paren, we expect that you intend $words to be array, which is to be converted into a list of string literals in the SQL statement.

IN '(".implode(' , ' , $words). ")"
   ^           ^^ ^^

It looks like you intended something like this:

IN ('" . implode("','",$words) . "')";
    ^            ^^ ^^            ^

If $words is empty, that will result in SQL text:

IN ('') 

If $words contains elements "abc","def", that will result in SQL text:

IN ('abc','def')

But again, examine the contents of the actual SQL text before it's sent to the database.


You may want to seriously consider the resulting SQL statement if one of the elements in $words happens to contain characters that could be interpreted as SQL text, for example:

"abc') OR 1=1; -- "

Classic SQL Injection vulnerability ala Little Bobby Tables http://xkcd.com/327/

spencer7593
  • 106,611
  • 15
  • 112
  • 140
0

say you have,

$words = ["a" ,"b","c","d"];  // i.e an array

then,

$val = implode(',' , $words) ; 


$q1="SELECT * FROM indexing WHERE keywords IN ($val)";

Do it this way.

Adeel Raza
  • 628
  • 5
  • 17
0

Firstly , you are using mysqli_query whereas you should be using prepared statements at least if not pdo.

$query = "SELECT <your code> FROM <your code> IN ('".implode("','",array_values($words))."') "; should work. And if you are looking for a solution in prepared statement, it has already been answered here.

Community
  • 1
  • 1
shortCircuit
  • 169
  • 2
  • 10