从下拉菜单(枚举)向mysql db插入所选值

时间:2013-11-18 06:02:30

标签: php

表单中有一个下拉列表,其中填充了mysql db中的值。下拉列表的表字段为enum类型。我正在尝试insert用户选择的值到数据库中。我只得到NULL的结果。如何从表格下拉列表中insert选择的值? SITE

PHP

<?php

$db_con = new mysqli(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

if(isset($_POST['submit'])) {

$db_insert  = $db_con->prepare("INSERT INTO academy (name, type, academy_id) VALUES (?,?,?,?)"); 
$db_insert->bind_param('ssi', $_POST['name'], $type_value, $_POST['acad_id']);
$db_insert->execute();

print_r($_POST);
}

?>
<form action="test7.php" method="POST">
        Name: <input type="text" name="name"></br>
        Type: 
            <?php

                $table_name = "academy";
                $column_name = "type";

                echo "<select id=\"$column_name\" name=\"$column_name\"><option>Select one</option>";
                $q = "SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE TABLE_NAME = '$table_name' AND COLUMN_NAME = '$column_name'";
                $r = mysqli_query($db_con, $q);

                $row = mysqli_fetch_array($r);
                //print_r($row);
                $enumList = explode(",", str_replace("'", "", substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE'])-6))));
                //print_r($enumList);
                foreach($enumList as $type_value){
                    echo "<option value='$type_value'>$type_value</option>";
                }
                echo "</select></br>";

            ?>
        Academy ID: <input type="text" id="acad_id" name="acad_id"></br>
    <input value="SAVE" name="submit" type="submit">
</form> 

CREATE TABLE IF NOT EXISTS `academy` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(25) DEFAULT NULL,
  `academy_id` int(11) DEFAULT NULL,
  `type` enum('INACTIVE','ACTIVE') DEFAULT 'ACTIVE',
PRIMARY KEY (`id`)
);

2 个答案:

答案 0 :(得分:2)

列不匹配('ssi',),

 $db_insert  = $db_con->prepare("INSERT INTO academy (name, type, academy_id) VALUES (?,?,?)"); 
 $db_insert->bind_param($_POST['name'], $_POST['type'], $_POST['acad_id']);

答案 1 :(得分:0)

if(isset($_POST['submit'])) {

$db_insert  = $db_con->prepare("INSERT INTO academy (name, type, status, academy_id) VALUES (?,?,?,?)"); 
$db_insert->bind_param('ssi', $_POST['name'], $_POST['type'], $_POST['acad_id']);
$db_insert->execute();

print_r($_POST);
}

无需将值设置为状态列??? 如果不需要,你应该删除一个问号&#39;?&#39;来自您的查询

if(isset($_POST['submit'])) {

$db_insert  = $db_con->prepare("INSERT INTO academy (name, type, academy_id) VALUES (?,?,?)"); 
$db_insert->bind_param('ssi', $_POST['name'], $_POST['type'], $_POST['acad_id']);
$db_insert->execute();

print_r($_POST);
}

如果需要,你应该添加&#39;添加你的bind_param和状态值,如下所示

if(isset($_POST['submit'])) {

$db_insert  = $db_con->prepare("INSERT INTO academy (name, type, status, academy_id) VALUES (?,?,?,?)"); 
$db_insert->bind_param('sssi', $_POST['name'], $_POST['type'], $status, $_POST['acad_id']);
$db_insert->execute();

print_r($_POST);
}