gpt4 book ai didi

php 在向数据库中插入一个值之前检查数据库中的值

转载 作者:行者123 更新时间:2023-11-30 23:07:23 26 4
gpt4 key购买 nike

我有这样的表格

<form id="formID" method="post" action="" enctype="multipart/form-data">
<input type="checkbox" name="attribute[]" value="Disk space"/>Disk space<br />
<input type="checkbox" name="attribute[]" value="Color"/>Color<br />
<input type="checkbox" name="attribute[]" value="Processor"/>Processor<br />
<input type="submit" name="save" id="save" value="save"/>
</form>

在 mysql 中我有一个数据库。数据库结构是这样的。

CREATE TABLE IF NOT EXISTS `ia_attributes` (
`attribute_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`attribute_name` text NOT NULL,
PRIMARY KEY (`attribute_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=186 ;


INSERT INTO `ia_attributes` (`attribute_id`, `attribute_name`) VALUES
(170, 'Color'),
(179, 'Disk space'),
(185, 'Processor');

在上面的表格中你可以看到我有复选框,我想一次插入所有的复选框,我这样写代码

<?php
$host = 'localhost';
$username = 'root';
$password = 'root';
$dbname = 'database';
$con=mysqli_connect($host,$username,$password);
mysqli_select_db($con,$dbname) or die ("no database");
<?php
if(isset($_POST["save"]) && isset($_POST["type"])){
$types = $_POST["type"];
if(sizeof($types) > 0 ){
foreach($types as $type){
$qry= '';
$result = mysqli_query($con,"SELECT COUNT(*) FROM `ia_attributes` where `attribute_name`='".$type."'");
if($result->num_rows == 1){
echo "<script>
alert('There are no fields to generate a report');
</script>";
}
else {
$qry = "INSERT INTO `ia_attributes`(`attribute_id`, `attribute_name`) VALUES ('', '".$type."')";
$sql_query = mysqli_query($con, $qry);
if($sql_query) {
echo "success";
}
else {
echo "error";
}
}
}
}
}

?>

在这里,无论我试图保存什么,它只显示警告框,没有用于生成报告的字段。给出的条件不起作用。那么有人可以告诉我如何解决这个问题吗?

最佳答案

执行选择查询,条件为 attribute_name = selected color in your database。然后检查它返回的结果数。如果它大于 0,那么它已经存在于您的数据库中,然后显示它已经存在的警报。

if(isset($_POST["save"]) && isset($_POST["attribute"])){
$attributes = $_POST["attribute"];
if(sizeof($attributes) > 0 ){

foreach($attributes as $attribute){
$qry= '';
$result = mysqli->query($con,"SELECT attribute_id FROM ia_attributes where attribute_name=$attribute"));

/* determine number of rows result set */
$row_cnt = $result->num_rows;
if($row_cnt > 0){
echo "<script>
alert('There are no fields to generate a report');
</script>";
}
else{
$qry = "INSERT INTO `ia_attributes`(`attribute_id`, `attribute_name`) VALUES ('', '".$attribute."')";
$sql_query = mysqli_query($con, $qry);
if($sql_query) {
echo "success";
}
else {
echo "error";
}
}

}
}
}

关于php 在向数据库中插入一个值之前检查数据库中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21282497/

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