从复选框中获取多个值并存储在DB php中
无法将多个复选框值存储到数据库中。不确定这是否是最有效的方法,但这是我唯一能想到的方法。如果有更好的方法,请分享。我仍然处于测试模式,所以还没有验证 来自DB的项目从复选框中获取多个值并存储在DB php中,php,mysql,pdo,Php,Mysql,Pdo,无法将多个复选框值存储到数据库中。不确定这是否是最有效的方法,但这是我唯一能想到的方法。如果有更好的方法,请分享。我仍然处于测试模式,所以还没有验证 来自DB的项目 $get_products = $db->prepare("select * from item where user_id = '$id' ORDER BY add_date"); $get_products->execute(); while ($row = $get_products->fetch(
$get_products = $db->prepare("select * from item where user_id = '$id' ORDER BY add_date");
$get_products->execute();
while ($row = $get_products->fetch())
{
$item_id = $row['item_id'];
$user_id = $row['user_id'];
$item_name = $row['item_name'];
$products .= "<br/><input type='checkbox' name='items[]' value='$item_id' />$item_name";
}
我看到的第一个问题是,在执行此操作时,您正在使用空白字符串覆盖
$items
变量:
$items = $_POST['items'];
$items = "";
这意味着您将在空白字符串上运行foreach
虽然存储复选框中的值的更好方法是只存储原始的$items
变量。这将把从表单接收到的值编码为JSON字符串,该字符串可以安全地存储在数据库中
然后,当您想从数据库中获取数据时,只需在json字符串上运行json\u decode()
,json字符串就会转换回数组
但是,如果希望从json\u decode()
返回关联数组,请确保将true传递到第二个参数,如下所示:
$indexed_array = json_decode($some_array);
$associative_array = json_decode($some_array, true);
编辑
如果数据是从表单传递的,这就是您在confirm.php文件中需要的:
if(isset($_POST['submit']))
{
$from = $_POST['from_id'];
$to = $_POST['to_id'];
$items = $_POST['items'];
if(empty($items))
{
$message = "no items in items";
exit;
}
$items = json_encode($items);
$sql = $db->prepare("INSERT into trans(from_id, to_id,items)VALUES(:from_id,
:to_id, :items");
$sql->bindValue('from_id', $from);
$sql->bindValue('to_id', $to);
$sql->bindValue('items', $items);
if($sql->execute())
{
header("Location: profile.php?user=1");
exit();
}
}
我把那行评论掉了,还是一无所获。当我将
项
保存到数据库时,是否使用varchar
类型保存它们?是的。此外,在将$items
的值保存到DB之前,您是否尝试过输出该值?@ShivanshuSrivastava更新的代码。当我尝试对项
数组进行编码时,我收到一个数组到字符串的转换错误。我得到了所有的值,虽然它显然是$items,而不是您在foreach中使用的数组,但是您可以使用“while”将所需内容与$items一起循环。我已经用confirm.php文件中所需的代码更新了我的答案。
$indexed_array = json_decode($some_array);
$associative_array = json_decode($some_array, true);
if(isset($_POST['submit']))
{
$from = $_POST['from_id'];
$to = $_POST['to_id'];
$items = $_POST['items'];
if(empty($items))
{
$message = "no items in items";
exit;
}
$items = json_encode($items);
$sql = $db->prepare("INSERT into trans(from_id, to_id,items)VALUES(:from_id,
:to_id, :items");
$sql->bindValue('from_id', $from);
$sql->bindValue('to_id', $to);
$sql->bindValue('items', $items);
if($sql->execute())
{
header("Location: profile.php?user=1");
exit();
}
}