gpt4 book ai didi

php - 如何在选择类别时将类别 ID 添加到另一个表?

转载 作者:行者123 更新时间:2023-11-29 14:06:11 24 4
gpt4 key购买 nike

我有两个表(帖子,类别)

CREATE TABLE post    
(pid INT(10) NOT NULL AUTO_INCREMENT,
post_title VARCHAR(255),
post_result VARCHAR(255),
post_content VARCHAR(500),
cid INT(10),
PRIMARY KEY (pid),
FOREIGN KEY (cid) REFERENCES category(cid));

CREATE TABLE category (
cid INT(10) NOT NULL AUTO_INCREMENT,
cname VARCHAR(50),
PRIMARY KEY (cid));

这是我的插入语句:

$id = isset($_POST['pid'])?$_POST['pid']:'';
$title=$_POST['post_title'];
$result=$_POST['post_result'];
$content=$_POST['post_content'];
$catid=$_POST['cid'];
$cat=$_POST['cname'];
$insertquery="INSERT INTO review (pid,post_title,post_result,post_content)
VALUES('','$title','$result','$content')";

我面临的问题是,在我的帖子表中,每条记录的类别 id ( cid ) 值都是 NULL。
如何让它存储所选类别的值。

这是我的表格:

<form id="create" action="insert.php" method="post">
<input type="text" name="post_title" placeholder="Title" /><br>
<input type="text" name="post_result" placeholder="Final comment" /><br>
<textarea name="post_content" placeholder="Review" ></textarea><br>

Category:
<select name=cname>
<option value="select"></option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
</select><br><br>

<input class="submit" name="submit" type="submit" value="Submit"/>

</form>

帮助获取输出。

最佳答案

首先我希望您从数据库中填充您的类别选择,并且value属性包含类别ID。话虽这么说,最好将 name 属性更改为 cid (因为这是您在 POST 中所期望的):

<select name="cid">

然后 var_dump($_POST) 将如下所示:

array(5) {
["post_title"]=>
string(2) "aa"
["post_result"]=>
string(2) "bb"
["post_content"]=>
string(2) "cc"
["cid"]=>
string(1) "2"
["submit"]=>
string(6) "Submit"
}

其次你可以放弃以下 php 行:

$id = isset($_POST['pid'])?$_POST['pid']:'';
$cat=$_POST['cname'];

因为您没有通过表单发送这些值,也没有使用它们。

第三你需要更正你的插入语句

$insertquery="INSERT INTO post (post_title,post_result,post_content,cid)
VALUES('$title','$result','$content','$catid')";

其他注意事项:

  • 您最好确保在客户端已选择类别名称,否则您在尝试在 post 中插入记录时会出错。
  • 正如 a1ex07 提到的,在放入数据库之前,您需要检查并清理所有用户输入
  • 切换到准备好的语句

关于php - 如何在选择类别时将类别 ID 添加到另一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14306350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com