我有这段代码,它从数据库中获取类别并将它们显示在下拉菜单上。Now, what I want to do, Is when something is selected and the button isset
, get the ID of that category (table: categories
,row category_id
) then submit it into (table: posts
,row category_id
). 我不知道如何获取在下拉列表中选择的类别的 ID。谢谢。
$db
变量是数据库连接。
这就是我到目前为止所得到的。这是向数据库提交数据:
include('../includes/db_connect.php');
if(isset($_POST['submit'])){
$newTitle = $_POST['newTitle'];
$newPost = $_POST['newPost'];
$newCategory = $_POST['newCategory'];
$my_date = date("Y-m-d H:i:s");
if(!empty($newPost))
if(!empty($newTitle)){
$sql="INSERT INTO posts (title, body, category_id)
VALUES('$newTitle', '$newPost', '$newCategory')";
$query = $db->query($sql);
if($query){
echo "Post entered to database";
}else{
echo "Error Submitting the data";
}
}
}
这是选择:
<textarea name="newPost" cols="176" rows="25"/></textarea><br>
<select name=""="newCategory" id="newCategory">
<option value="0">Select category</option>
<?php
$result = mysqli_query($db, "SELECT * FROM categories");
if ( $result ) {
while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
echo '<option value="' . $row['category'] . '">' . $row['category'] . '</option>';
}
} else {
echo 'Couldn\'t fetch Categories from MySQL.';
}
?>
Ps - 我知道这很容易注射,你不需要告诉我,请回答问题:)