0

Here is the database

CREATE TABLE IF NOT EXISTS `student` (
  `id` int(11) NOT NULL,
`name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `student`
ADD PRIMARY KEY (`id`);
ALTER TABLE `student`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Here is the HTML part: jsFiddle

And Here is the PHP part inserting data to mysql:

<?php
$connect = mysql_connect('localhost','root','');
if (!$connect) {
   echo mysql_error();
}
$db = mysql_select_db('demo');
if (!$db) {
  echo mysql_error();
} 
$all_names ="";
if(isset($_POST["mytext"])){   
   foreach($_POST["mytext"] as $key => $text_field){
      $all_names .= $text_field .", ";
 }
}

$result = "INSERT INTO student ( name ) VALUES( $all_names )";
$insert_row  = mysql_query($result);
if(!$insert_row){
   echo $result;
}

Getting Error inserting value to database:

INSERT INTO student ( name ) VALUES( dffd, )
Russell
  • 1,624
  • 5
  • 23
  • 43

2 Answers2

2

I don't see whole picture yet. What is the real value returned by $_POST["mytext"]?

But my guess you should at least change your loop to:

foreach($_POST["mytext"] as $key => $text_field){
      if ($all_names == '') {
          $all_names .=  "( '".mysql_real_escape_string($text_field) ."') ";
      } else {
          $all_names .=  ",( '".mysql_real_escape_string($text_field) ."') ";
      }
 }

and your query to:

 $sql = "INSERT INTO student ( name ) VALUES $all_names ";
Alex
  • 16,739
  • 1
  • 28
  • 51
1

Change

   foreach($_POST["mytext"] as $key => $text_field){
      $all_names .= $text_field .", ";
   }

to

$all_names = "'" . implode("'), ('", $_POST["mytext"]) . "'";
Grzegorz Adam Kowalski
  • 5,243
  • 3
  • 29
  • 40