无法将多个复选框值存储到数据库中。不知道这是否是最有效的方法,但这是我唯一能想到的。如果有更好的方法,请分享。我仍处于测试模式,因此尚无验证。
来自数据库的项目$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 .= "$item_name";
}
形成
处理
if(isset($_POST['submit']))
{
$from = $_POST['from_id'];
$to = $_POST['to_id'];
$items = $_POST['items'];
if(empty($items))
{
$message = "no items in items";
exit;
}
foreach($items as $i)
{
$items .= $i. "|";
}
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();
}
最佳答案
我看到的第一个问题是,执行此操作时,您正在用空白字符串覆盖$items变量:$items = $_POST['items'];
$items = "";
这意味着您将在空白字符串上运行foreach。
尽管存储复选框中值的更好方法是仅json_encode()原始$items变量。这会将您从表单收到的值编码为JSON字符串,可以安全地存储在数据库中。
然后,当您想将数据从数据库中取出时,只需对JSON字符串运行json_decode(),JSON字符串将被转换回数组。
但是,如果希望从json_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();
}
}