Buki
Buki

Reputation: 127

Retrieve all data from SQL array LIKE a given value

I'm trying to retrieve all the data id from a database where their tags(array) is like a given value. This is what I have done so far...

$new_string = 'nice phone';
$construct = mysql_query("SELECT tag_array, name, id FROM details 
WHERE tag_array LIKE $new_string%")
or die("<p>died 20: $construct<br>" . mysql_error());

while($getThis = mysql_fetch_array($construct)){
echo $getThis['id'].'<br />';
echo stripslashes($getThis['name']).'<br />';
}

It doesn't work ATALL. Could you please point me to the right direction? I'm really struggling!!

Upvotes: 0

Views: 467

Answers (2)

Adam Arold
Adam Arold

Reputation: 30558

You should sanitise the data before putting it in the query like:

  $new_string = "blah...; DROP TABLE tag_array; #";
  $sql = mysql_real_escape_string($new_string);
  $sql = "SELECT tag_array, name, id FROM details WHERE tag_array LIKE %'$sql'%"

This is not enough though it just helps preventing sql inject, consider using regular expressions to clean the data. If you don't yet know about regexp check out this site: regexp info. It helped me mutch.

Upvotes: 0

enoyhs
enoyhs

Reputation: 2069

You should put $new_string in quotes.

NOTE It is very bad practice and you should always escape all variables you are passing to SQL. You should really read up on SQL injection and other security issues.

Also if you want to match $new_string anywhere in tag_array (which you most likely want), you need to add dollar sign in front of it too. You can read up more at MySQL reference manual.

So in the end:

"SELECT tag_array, name, id FROM details WHERE tag_array LIKE '%" . mysql_real_escape_string($new_string) . "%'"

Upvotes: 1

Related Questions