Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a $_POST and add to database

Tags:

foreach

php

mysql

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);            

    }
like image 409
Becs Carter Avatar asked Nov 13 '22 09:11

Becs Carter


1 Answers

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

like image 152
Kumar Saurabh Sinha Avatar answered Nov 14 '22 21:11

Kumar Saurabh Sinha