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
WHEREtag
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
WHEREtag
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.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With