将所选文本发送到数据库

时间:2016-02-22 17:22:00

标签: php sql

我正在尝试将数据发送到我的数据库。用户需要从下拉列表中选择产品。通过单击发送脚本将其发送到数据库。但是当我查看数据库时,我发现发送的数据是错误的。脚本发送选定的ID而不是选定的名称(文本)。我想发送名称而不是id。我该如何解决这个问题?

的index.php

<div class="form-group">
<label>Product</label>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM forms";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "<select class='form-control select2' id='product1' name='product1' style='width: 100%;'>";
     echo "<option selected disabled hidden value=''></option>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
                      echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
     }                   
echo "</select>";
} else {
     echo "0 results";
}

$conn->close();

?>  
</div><!-- /.form-group -->

send.php

<?php 
session_start(); 
?>

<html>
<body>

<table>
<?php
$correct = true;

$product1 = $_POST['product1'] ;

?>
</table>

<?php
if($correct){
    $db = new PDO('mysql:host=localhost;dbname=database', 'root', '');

    $query = "INSERT INTO forms2 (product1) VALUES (?)";
$stmt = $db->prepare($query);
$stmt->execute(array($product1));

            header("Location: ./print.php");  
}else{

    echo "<br /><br />Error<br />\n";
}
?>

</body>
</html>

0 个答案:

没有答案