如何动态保存数据到数据库

时间:2013-05-14 06:59:20

标签: php javascript jquery mysql

JQUERY CODE

 $(document).ready(function () {
    $("#add").click(function () {
        $(".left .inputs").append("<li><input type ='text' name='name[]' class='txtbox1'></li>");
        $(".right .inputs").append("<li><input type ='text' name='grade[]' class='txtbox'></li>");
    });
 });

我的PHP代码

<?php
    $con = mysql_connect ("localhost","root","") or die('cannot connect to database error: '.mysql_error());
    if (isset($_POST['name']) && isset($_POST['grade']))
    {

        $desk_report = $_POST['name'];//contains array value
        $desk_action = $_POST['grade'];//contains array value
        foreach($desk_report as $key=>$user) { //Loop through arrays
            if (!empty($desk_report[$key]) && !empty($desk_action[$key])) {
                mysql_select_db("quickbook", $con);
                $sql = "INSERT INTO student_reg(relative_name,relative_grade) VALUES ('$desk_report[$key]','$desk_action[$key]')";
                if ($sql_run = mysql_query($sql)) {
                    echo 'ok.'; 
                } else {
                    echo '*Sorry, we couldn\'t register you at this time. Try again later.';
                }
            }
        }
    }
?>

我想将输入数据添加到database.i创建一个代码。但这不起作用。你可以帮我吗?

1 个答案:

答案 0 :(得分:1)

检查您使用的数据库是否存在, 尝试你的代码

<?php
    $con = mysql_connect ("localhost","root","") or die('cannot connect to database error: '.mysql_error());

    //add this line to your code here instead of in for loop
    mysql_select_db('quickbook',$con) or die("Could not select database!");
    if (isset($_POST['name']) && isset($_POST['grade']))
    {
        $desk_report = $_POST['name'];//contains array value
        $desk_action = $_POST['grade'];//contains array value
        foreach($desk_report as $key=>$user) { //Loop through arrays
            if (!empty($desk_report[$key]) && !empty($desk_action[$key])) {
                $sql = "INSERT INTO student_reg(relative_name,relative_grade) VALUES ('$desk_report[$key]','$desk_action[$key]')";
                if ($sql_run = mysql_query($sql)) {
                    echo 'ok.'; 
                } else {
                    echo '*Sorry, we couldn\'t register you at this time. Try again later.';
                }
            }
        }
    }
?>