What I trying to do is loop through a text input where the user enters tags for a blog post. I want to add each tag to the database if it doesn't already exist.
The actual query string below works when I test in in the database.
However I think that my loop syntax is maybe not quite right cos I am getting nothing added to the DB.
Can anyone spot an error in my loop causing my 'add to database' fail?
Thanks in advance for your help!
foreach ($_POST['__tags'] as $key=>$ls_value) {
$value = strtolower(mysql_real_escape_string($ls_value));
mysql_query("INSERT INTO `table` (`field`)
SELECT * FROM (SELECT '$value') as tmp
WHERE NOT EXISTS (
SELECT `field` FROM `table` WHERE `field` = '$value')
LIMIT 1") or trigger_error(mysql_error(), E_USER_ERROR);
}
try using the following code:
if(is_array($_POST['__tags']))
{
foreach ($_POST['__tags'] as $key=>$ls_value) {
$value = strtolower(mysql_real_escape_string($ls_value));
mysql_query("INSERT INTO table (field)
SELECT * FROM (SELECT '".$value."') as tmp
WHERE NOT EXISTS (SELECT field FROM table WHERE field = '".$value."') LIMIT 1") or trigger_error(mysql_error(), E_USER_ERROR);
}
}
Please using proper PDO or prepared statement and mysql_query is deprecated, instead use mysqli functions
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