使用Ajax + php在mysql表中同时添加多条记录

时间:2012-01-30 05:55:52

标签: php mysql ajax

我正在尝试使用PHP在MySQL数据库中一次插入多行。我想在3个不同的行中插入a,b,c,但它以1,b,c格式插入1行。

我的代码如下所示,它没有给我任何错误,因为代码完美无缺,但我无法得到我想要的结果。

<?php
require_once('conn.php');
$name = $_POST['name'];
 if($name)
 {
    foreach($name as $std_name)
    {
    $student[] = $std_name;
    // implode($c); i.e a,b,c etc
    }
 }
$sql = "INSERT INTO `tbl_student` 
 (`student_name`) 
 VALUES 
 ('".implode($student, ',')."');";
 $res = mysql_query($sql);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript"> 

    var nFloor = "";    

    function removeField(nField){

        nField.parentNode.parentNode.removeChild(nField.parentNode);
    }

    function insertField(){

        var newFieldContainer = document.createElement('div');
        var newFieldLabel = document.createElement('label');
        newFieldLabel.innerHTML = "Student Name:&nbsp;&nbsp;&nbsp;";        
        var newField = document.createElement('input');
        newField.type = "text";
        newField.name = "vipInfo[]";
        newFieldContainer.appendChild(newFieldLabel);
        newFieldLabel.appendChild(newField);
        var deleteBtn = document.createElement('input');
        deleteBtn.type = "button";
        deleteBtn.value = "Remove";
        deleteBtn.style.marginLeft = "5px";
        deleteBtn.onclick = function(){removeField(this)};
        newFieldContainer.appendChild(deleteBtn);
        document.forms[0].insertBefore(newFieldContainer,nFloor);
    }

    function init(){

        var insertBtn = document.getElementById('newFieldBtn')
        insertBtn.onclick = function()
            {
             insertField();
            }
        nFloor = insertBtn;     
    }

    navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);    

</script>
</head>
    <body>
        <form action="" method="post">

            <div class="field"><label>Student Name:&nbsp;&nbsp;&nbsp;<input type="text" name="name[]"></label></div>

            <input type="button" id="newFieldBtn" value="New Field"> 
            <input type="submit" name="submit" value="Submit">

        </form>
    </body>
</html>

2 个答案:

答案 0 :(得分:0)

提出此查询

$sql = "INSERT INTO `tbl_student` 
 (`student_name`) 
 VALUES 
 ('".implode($student, ',')."');";
 $res = mysql_query($sql);

foreach块内 不要使用implode使用,或者使用以下查询作为

$sql = "INSERT INTO `tbl_student` 
 (`student_name`) 
 VALUES 
 ('". $std_name."');";

所以它会在不同的行中添加每一个

答案 1 :(得分:0)

使用此:

$val="('".implode("'), ('",$student)."')";
        $sql = "INSERT INTO `tbl_student`
 (`student_name`) VALUES ".$val.";";