-1

How can I write the insert statement for the following type of scenario?

<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<input type="text" name="tbxt[]" />
<input type="text" name="tbxt[]" />
<input type="text" name="tbxt[]" />
<input type="text" name="tbxt[]" />
<input type="text" name="tbxt[]" />
 <input type="submit" name="dosubmit" value="Next" class="submitbtn" />
<form>

I tried like the below which didn't work for me

<?php    
    if (isset($_POST['dosubmit'])) {
    foreach ($_POST['tbxt'] as $tbxt)
    {
    for ($i=0; $i<5; $i++)
    {
           $doquery = mysql_query("INSERT INTO mylist(`itemname`) VALUES('".$tbxt[$i]."')") or die(mysql_error());
        }
    }
    }
?>

Also, how can I write the array count instead of $i<5

Karthik Malla
  • 5,570
  • 12
  • 46
  • 89
  • **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Aug 09 '14 at 10:46
  • @Quentin - Yeah, I knew that. Will change it to MySQLi. Thanks – Karthik Malla Aug 09 '14 at 10:47

2 Answers2

1

You even dont need the second for loop

foreach ($_POST['tbxt'] as $tbxt)
    {

           $doquery = mysql_query("INSERT INTO mylist(`itemname`) VALUES('".$tbxt."')") or die(mysql_error());

    }

Its recommended not to use mysql_* functions. Instead use mysqli_* or pdo functions.

fortune
  • 3,361
  • 1
  • 20
  • 30
0

just one foreach will do

foreach($_POST['tbxt'] as $tbxt){ *insert values from $tbxt by query*}