注意将PHP配置文件中的magic_quotes_gpc设成On并重启Apache,这样来自GET/POST/Cookie的数据自动会做类似这样的处理:在单引号('),双引号("),斜杆()和NUL's前加,如果该值为Off,您可以用addslashes达到同样的效果.
本程序使用这样一个表:
use test;
create table batch(
id int unsigned auto_increment primary key,
name varchar(50),
email varchar(255)
);
*/
?>
<html>
<head><title>向数据库中批量插入数据一例</title></head>
<body>
<form action="<?echo $PHP_SELF;?>" method="post">
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<th>name</th>
<th>email</th>
</tr>
<?
$num_input = 4;
for($i=0;$i<$num_input;$i++){
?>
<tr>
<td><input type="text" name="name[]" maxlength="50" size="15"></td>
<td><input type="text" name="email[]" maxlength="255" size="80"></td>
</tr>
<?
}
?>
<tr align="center">
<td colspan="2"><input type="submit" value="提交"></td>
</tr>
</table>
</form>
<?
$server = mysql_connect('localhost','test','') or die('无法连接localhost服务器');
mysql_select_db('test',$server) or die('无法连接test数据库');
if(isset($name) and isset($email)){
$rows = 0;
$count = count($name);
$sql = 'insert batch(name,email) values ';
for($i=0;$i<$count;$i++){
if($name[$i]!='' and $email[$i]!=''){
$sql .= '('' . $name[$i] . '','' . $email[$i] . ''),';
$rows++;
}
}
if($rows>0){
$sql = substr($sql,0,strlen($sql)-1);
mysql_query($sql) or die($sql . '出错');
}
}
$sql = 'select * from batch';
$rst = mysql_query($sql,$server) or die($sql . '出错');
echo '<table border="1" cellspacing="0" cellpadding="0">';
echo '<tr>';
$num_fields = mysql_num_fields($rst);
for($i=0;$i<$num_fields;$i++){
echo '<th>' . mysql_field_name($rst,$i) . '</th>';
}
echo '</tr>';
while($row=mysql_fetch_row($rst)){
echo '<tr>';
for($i=0;$i<$num_fields;$i++){
echo '<td>' . $row[$i] . '</td>';
}
echo '</tr>';
}
echo '</table>';
mysql_close($server) or die("无法与服务器断开连接");
?>
</body>
</html>
|