Scroll through $ _POST and add to the database

What I'm trying to do is loop through text input into which the user enters tags for a blog post. I want to add each tag to the database if it does not already exist.

The actual query line below works when I test in the database.

However, I think that my loop syntax is probably not quite right, because I am not adding anything to the database.

Can someone detect an error in my loop causing my add to the database to 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);            

    }
+5
source share
3 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 the correct PDO or prepared statement, and mysql_query is deprecated, use mysqli functions instead

+1

:

PHP:

<?php 

$tags = $_POST['tags'];

foreach ($tags as $tag){
$value = strtolower(mysql_real_escape_string($tag));
$sel_tag = mysql_query("select * from `table` where `field`='$value'")or die(mysql_error());
$num_rows = mysql_num_rows($sel_tag);
if($num_rows > 0){
echo "Tag Already Exists";
}
else {
$ins_tag = mysql_query("insert into `table` (`field`) values ('$value');")or die(mysql_error());
echo "Tag Successfully Inserted";
}
}

?>

HTML:

<form action="" name="tags" method="post">
<p>Please select the tags names : </p>
<p>
<input type="checkbox" name="tags[]" value="tag1"> Tag1
<input type="checkbox" name="tags[]" value="tag2"> Tag2
<input type="checkbox" name="tags[]" value="tag3"> Tag3
</p>
<p><input type="submit" name="tag_submit" value="Submit"></p>
</form>

, .

0

, , . .

post.php

 <?php  
        $keys=array();
        $values=array();    
        foreach ($_POST as $key=>$ls_value) {
            $keys[]=$key;
            $values[]="'".mysql_real_escape_string($ls_value)."'";      
        }
        echo $fileds=implode(",", $keys);
        echo $values=implode(",", $values);
  ?>

form.html

<form action="post.php" method="post">
  <input type="text" value="123" name="number"/>
  <input type="text" value="firstname" name="name"/>
  <input type="submit" value="submit"/>
</form>
0
source

All Articles