多个列表框值未使用PHP插入MySQL数据库

时间:2014-12-13 16:13:27

标签: php jquery html mysql database

我试图将多个列表框值插入数据库,但无论如何这些值都没有插入到数据库中。我认为我的PHP文件存在一些问题

这是我的Javascript文件

$(document).ready(function() {



       jQuery("#skill-form").validationEngine();



            $("#skill-form").on("submit",function(e) {

                e.preventDefault();

                 if($("#skill-form").validationEngine('validate')) {
                    var form_data = $( "form" ).serialize();
                        $.post( "insert.php",{form_values : form_data},function( data ) {
                        var Data =  jQuery.parseJSON(data);



                  });

       } else {
            return false;
        }


       });

});

这是我的HTML文件

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">

        <link href="css/bootstrap.min.css" rel="stylesheet">


         <link rel="stylesheet" href="css/validationEngine.jquery.css">



    </head>

<body>





 <form class="form-horizontal" role="form" action="#"  method="post" id="skill-form">

  <div class="form-group">

                <br>  <br> <br> <br> <br> <br> <br>
          <label class="col-sm-2 control-label">States:</label>
            <div class="col-sm-6">


<select name="which_state[]" id="which_state" class="form-control" multiple="multiple" data-validation-engine="validate[required]"  data-errormessage-value-missing="Please Select any one option" >
                            <option value="Colorado">Colorado</option>
                            <option value="Florida">Florida</option>
                            <option value="Illinois">Illinois</option>
                            <option value="Michigan">Michigan</option>
                            <option value="Minnesota">Minnesota</option>
                            <option value="Ohio">Ohio</option>
                            <option value="Texas">Texas</option>
                            <option value="Wisconsin">Wisconsin</option>
</select>

</div>

</div>

        <div class="form-group">
          <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-primary" id="register" name="submit">Submit</button>
          </div>


</form>


    <script  src="js/jquery.js"></script>



<script type="text/javascript" src="js/jquery.validationEngine-en.js"></script>

       <script type="text/javascript" src="js/jquery.validationEngine.js"></script>



       <script type="text/javascript" src="js/managestage.js"></script>



</body>
</html>

这是我的PHP文件

<?php

  require_once("dbcon.php");

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
    $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

    switch ($theType) {
        case "text":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "long":
        case "int":
          $theValue = ($theValue != "") ? intval($theValue) : "NULL";
          break;
        case "double":
          $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
          break;
        case "date":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "defined":
          $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
          break;
    }
    return $theValue;
}


if(isset($_POST["form_values"]))
{
     $form_data = urldecode($_POST["form_values"]);

     preg_match_all('#(\w+)=([^&=]*)(?:&|$)#', $form_data, $matches, PREG_SET_ORDER); 
     $result = array();
       $i = 0;    
          foreach ($matches as $m) {
             list(, $key, $value) = $m;
          if (!strlen($value)) { 
             $i = (int)$key;
          } else {
           $result[$i][$key] = $value;
         }
}


        $which_state = $result[0]["which_state"];



      $insertSQL = sprintf("INSERT INTO test1 (States) VALUES (
                %s
            )", 
                           GetSQLValueString(implode(',', $_POST['which_state']), "text"));


        try
        {

          $query_insert = $db->prepare( $insertSQL );
          $result_insert = $query_insert -> execute(array(':which_state'=>$which_state));

        }
    catch(PDOException $ex)
        {

            die("Failed to run query: " . $ex->getMessage());
        } 

}
    ?>

1 个答案:

答案 0 :(得分:0)

我简化了你的代码,因为我假设你正在使用PDO或Msql将你的值作为字符串传递。它将所选项连接为数组中的字符串,并使用execute()将数组插入数据库。

<?php
if(isset($_POST['submit'])){//to run PHP script on submit
    if(isset($_POST['which_state'])){
        $states = implode(",",$_POST['which_state']);
        $paramArray = array($states);
    }
    $insertSQL = "INSERT INTO test1 (States) VALUES (?)";
    $query_insert = $db->prepare( $insertSQL );
    $result_insert = $query_insert -> execute($paramArray);
}
?>
<form method="POST" action="#">
<select name="which_state[]" id="which_state" class="form-control" multiple="multiple" data-validation-engine="validate[required]"  data-errormessage-value-missing="Please Select any one option" >
                            <option value="Colorado">Colorado</option>
                            <option value="Florida">Florida</option>
                            <option value="Illinois">Illinois</option>
                            <option value="Michigan">Michigan</option>
                            <option value="Minnesota">Minnesota</option>
                            <option value="Ohio">Ohio</option>
                            <option value="Texas">Texas</option>
                            <option value="Wisconsin">Wisconsin</option>
</select>
<input type="submit" name="submit" value="Submit">

示例查询INSERT INTO test1 (States) VALUES (?)

示例值array(1) { [0]=> string(16) "Florida,Illinois" }