Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

breaking up strings with explode and foreach

I'm Trying to get a php string to break down into individual words, search for them in a database and then add the results into another database..

I currently have the string like this

"SDGCC, ARISE, SDGFS"

I want to search in the login tags table for tags LIKE these words i'm using this

SELECT * FROM logintags WHERE tag LIKE '%string%'

so that each tag is taken from the string i've tried using explode and foreach but it doesn't seem to be getting the desired effect.

$string = $_POST['tags'];

$tags = explode(',' $string);

foreach($tags as $key) {

$query = mysql_query("SELECT * FROM dept_logintags WHERE tag LIKE '%".$key."%'"); $r = mysql _fetch _object($query);

$insert = mysql_query("INSERT INTO briefings_logintags (id, briefing_id, logintag_id) VALUES (NULL, '$id', '".$r->id."')");

}

the effect i'm trying to create is for each tag create a reference between the tag id and the briefing id...

However it seems only to be putting one correct entry in the database.

like image 717
Llanilek Avatar asked Sep 22 '09 11:09

Llanilek


2 Answers

Try

$tags = explode(',',$string);

foreach($tags as $key) {    
    echo '"'.$key.'"<br/>';    
}

My guess is that you are getting a space before ARISE and SDGFS.

Also, make sure you always escape strings properly before putting them into MySQL queries!! Otherwise someone can send tainted input to your server and wreak havoc on your database. (This is called a SQL injection.)

like image 157
Artelius Avatar answered Oct 02 '22 18:10

Artelius


If there is a space after the comma in your original string, then explode() will return something like ["SDGCC", " ARISE", " SDGFS"].

This will cause your LIKE clause to only match the first word. Try using trim():

$word=trim($key);
$safe=mysql_real_escape_string( $word );
$query=mysql_query("SELECT * FROM dept_logintags WHERE tag LIKE '%".$safe."%'");

EDIT: As Artelius mentioned, always escape user-submitted data to prevent SQL injection.

like image 25
ctford Avatar answered Oct 02 '22 18:10

ctford