因此,当我尝试从我的数据库中获取类别的名称时,例如使用此代码将是“信息与技术”、“数学与物理”、“离题”
<form method="POST" action="create_sub_cat.php">
<input type="text" name="sub_cat_name" value="" /><br>
<input type="text" name="sub_cat_desc" value""/><br>
<?
$get_cats = $dbh->prepare("SELECT * FROM forum_categories");
$get_cats->execute();
?>
<select name="cat_selection">
<?
while($cat = $get_cats->fetch(PDO::FETCH_OBJ)) {
echo '<option value='.$cat->cat_name.'>'.$cat->cat_name.'</option>';
}
?>
</select>
<input type="submit" value="Create Category!" name="create_sub_cat">
</form>
并将类别名称存储为 $selected_cat = $_POST['cat_selection']; 并回显它只会回显第一个单词,例如,如果我选择“信息与技术”,它只会回显“信息”,或者如果我选择“数学与物理”,它只会回显“数学”等. 这是完整的代码,这样你就知道我要做什么了。
<?php
if(isset($username) && $user_level == 3) {
?>
<div id="userbar">
<div id="announcement">Hello <?php echo '<a href=user.php?id='.$poster_id.'>'.$username.'<a>';?>
<a href="log_out.php">Log out</a></div>
</div>
<div id="menubar">
<ul id="menu">
<li ><a href="index.php" >Home</a></li>
<li ><a href="forum.php" >Forum</a></li>
<li ><a href="guides.php" >Guides</a></li>
<li ><a href="esports.php">E-Sports</a></li>
</ul>
</div>
<form method="POST" action="create_sub_cat.php">
<input type="text" name="sub_cat_name" value="" /><br>
<input type="text" name="sub_cat_desc" value""/><br>
<?
$get_cats = $dbh->prepare("SELECT * FROM forum_categories");
$get_cats->execute();
?>
<select name="cat_selection">
<?
while($cat = $get_cats->fetch(PDO::FETCH_OBJ)) {
echo '<option value='.$cat->cat_name.'>'.$cat->cat_name.'</option>';
}
?>
</select>
<input type="submit" value="Create Category!" name="create_sub_cat">
</form>
<?php
}
else {
die("You don't have the access to this page.");
}
$sub_cat_name = $_POST['sub_cat_name'];
$sub_cat_desc = $_POST['sub_cat_desc'];
$selected_cat = $_POST['cat_selection'];
if(isset($_POST['create_sub_cat'])) {
try{
echo $selected_cat;
$cat_id = $dbh->prepare("SELECT * FROM forum_categories WHERE cat_name = :cat");
$cat_id->bindParam(':cat', $selected_cat, PDO::PARAM_STR);
$cat_id->execute();
$fetch_cat_id = $cat_id->fetch(PDO::FETCH_OBJ);
$fetched_cat_id = $fetch_cat_id->id;
$create_sub_cat = $dbh->prepare("INSERT INTO forum_sub_categories (cat_id, sub_cat_name, sub_cat_description) VALUES (:cat_id, :sub_cat_name, :sub_cat_desc)");
$create_sub_cat->bindParam(':cat_id', $fetched_cat_id, PDO::PARAM_INT);
$create_sub_cat->bindParam(':sub_cat_name', $sub_cat_name, PDO::PARAM_STR);
$create_sub_cat->bindParam(':sub_cat_desc', $sub_cat_desc, PDO::PARAM_STR);
$create_sub_cat->execute();
}catch(PDOException $e){
echo "An error occured";
error_log($e->getMessage());
}
}
?>