如何在MySql中添加Varchar复选框值?

时间:2016-08-10 08:06:02

标签: php mysql checkbox

我正在尝试将复选框中的Varchar值添加到mysql中,并在选中的复选框中添加字符串“1”。我怎样才能添加如下的Varchar值?

<?php
if (isset($_POST['dr_add'])) {
  $lightv = isset($_POST['l_vehicle']);
  $van = isset($_POST['van']);
  $truck = isset($_POST['truck']);
  $trailer = isset($_POST['tr_trailer']);
  mysql_query("INSERT INTO driving(user_id, country,l_vehicle,van, truck , tr_trailer) VALUES('$user->employeeid','$lightv','$van','$truck','$trailer')") or die(mysql_error());
}
?>
<input type="checkbox" name="l_vehicle" value="Light Vehicle"/>Light Vehicle
<input type="checkbox" name="van" value="Van">Van
<input type="checkbox" name="truck" value="Truck"/>Truck
<input type="checkbox" name="tr_trailer" value="Truck&Trailer"/>Truck&Trailer

2 个答案:

答案 0 :(得分:3)

您正在使用$trailer = isset($_POST['tr_trailer']);,这是错误的:

以下代码的用户:

 $trailer = isset($_POST['tr_trailer'])?$_POST['tr_trailer']:"";

将此选项用于所有复选框

答案 1 :(得分:1)

  

isset - 确定变量是否设置且不是NULL

更新代码

<?php
if (isset($_POST['dr_add'])) {
  $lightv = isset($_POST['l_vehicle']) ? $_POST['l_vehicle'] : "";
  $van = isset($_POST['van']) ? $_POST['van'] : "";
  $truck = isset($_POST['truck']) ? $_POST['truck'] : "";
  $trailer = isset($_POST['tr_trailer']) ? $_POST['tr_trailer'] : "";

  mysql_query("INSERT INTO driving(user_id, country,l_vehicle,van, truck , tr_trailer) VALUES('$user->employeeid','$lightv','$van','$truck','$trailer')") or die(mysql_error());
}
?>

[注意The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead ]

<强>的mysqli

(其中,$con是连接)

$stmt = mysqli_prepare($con, "INSERT INTO driving(user_id,country,l_vehicle,van,truck,tr_trailer) VALUES (?, ?, ?,?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'dsssss',$user->employeeid,$lightv,$van,$truck,$trailer);

阅读Prepared Statements