将每行数据插入数据库

时间:2015-11-19 00:59:33

标签: php mysql

如何将每行中用户插入的数据保存到数据库中? This form is blank and user will insert the following data like Name, Mark, and Gred for every row depends on the no of student

this is example inserted data by user and when user click submit button, all the data in every row will save into database. So How do i do that?



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<?php

//First we need to make a connection with the database
$host='localhost'; // Host Name.
$db_user= 'root'; //User Name
$db_password= '';
$db= 'student'; // Database Name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());

$query = "INSERT INTO student_info (No, Name, Mark, Gred) VALUES ";
for ($i = 1; $i < count($_POST['No']); $i++) {
    $query .= " ({$_POST['No'][$i]}, '{$_POST['Name'][$i]}', '{$_POST['Mark'][$i]}', '{$_POST['Gred'][$i]}'),";
}

mysql_close($conn);
 
?>


<form id="form1" name="form1" method="post" action="">
  <table width="800" border="2" align="center">
    <tr>
      <td>NO</td>
      <td>NAME</td>
      <td>MARKS</td>
      <td>GRED</td>
    </tr>
    <tr>
      <td>1</td>
      <td><label for="Name"></label>
      <input type="text" name="Name[]" id="Name" /></td>
      <td><label for="Mark"></label>
      <input type="text" name="Mark[]" id="Mark" /></td>
      <td><label for="Gred"></label>
      <input type="text" name="Gred[]" id="Gred" /></td>
    </tr>
    <tr>
      <td>2</td>
      <td><label for="Name"></label>
      <input type="text" name="Name[]" id="Name" /></td>
      <td><label for="Mark"></label>
      <input type="text" name="Mark[]" id="Mark" /></td>
      <td><label for="Gred"></label>
      <input type="text" name="Gred[]" id="Gred" /></td>
    </tr>
  </table>
  <p>
    <center><input type="submit" name="SubmitButton" id="SubmitButton" value="Submit" /></center>
  </p>
</form>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我假设您已使用MySQLi或PDO连接到数据库,并且位于本地服务器上。

为此,您需要使用mySQL“INSERT”语句;

    INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');

如果这是你需要的,请研究 - http://www.w3schools.com/sql/sql_insert.asp

祝你好运