gpt4 book ai didi

PHP多个复选框到数据库

转载 作者:搜寻专家 更新时间:2023-10-31 22:03:20 24 4
gpt4 key购买 nike

你好,我一直在尝试使用多个复选框将信息输入数据库,我使用 [] 和复选框名称,但“数组”被保存到数据库。我应该输入什么代码以及在哪里输入才能正常工作?谢谢!

这是我的表单代码:

<?php
require_once('connection.php');

if(isset($_GET['process']))

{
$query = "Insert INTO `lista_precios` (Marca) values('$_POST[Marca]')";
//echo $query; exit;
$result = mysql_query($query) or die(mysql_error());
if(!$result)
{
$msg = "not Inserted";
}
else
{
$msg = "Inserted";
header("location:form.php?m=".$msg);
}
}
?>

<method="post" action="form.php?process">
<p>MARCA: <br><br>
<input type="checkbox" name="Marca" value="ACER">ACER
<input type="checkbox" name="Marca" value="AOC">AOC
<input type="checkbox" name="Marca" value="APPLE">APPLE

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


</form>

这是我的连接:

<?php


$link=mysql_connect("xxxx","xxxx","xxxx");
$database='xxxxxxx';
if (!$link)
die('Failed to connect to Server'.mysql_error());
$db=mysql_select_db($database, $link);
session_start();
if(!$db)
die('Failed to select Data Base '.mysql_error());


?>

最佳答案

首先您需要设置您的复选框名称并将它们变成name=Marca[]

<form method="post" action="form.php?process">
<p>MARCA: <br><br>
<input type="checkbox" name="Marca[]" value="ACER">ACER
<input type="checkbox" name="Marca[]" value="AOC">AOC
<input type="checkbox" name="Marca[]" value="APPLE">APPLE

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

然后在您的 form.php 上处理这些值:

注意:你必须明白,你不能只是将 $_POST['Marca'] 并连接成字符串,你必须获取每个值并构建插入查询。

if(isset($_GET['process'])) {
$marca = isset($_POST['Marca']) ? $_POST['Marca'] : null;
if(count($marca) < 3) {
// your validation that no checkboxes were selected
$msg = 'You need to select at least 3 values';
header("Location: form.php?m=".$msg);
}

$values = implode(',', $marca);
$statement = "INSERT INTO `lista_precios` (`Marca`) VALUES ('$values');";
// should result into
// INSERT INTO `lista_precios` (`Marca`) VALUES ('ACER,AOC,APPLE');
// then continue on your query code
$query = mysql_query($statement);
$msg = ($query && mysql_affected_rows() > 0) ? 'Inserted' : 'Not Inserted';
header("Location: form.php?m=".$msg);
}

关于PHP多个复选框到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23508056/

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