我如何通过php中的复选框更新sql记录?

时间:2014-06-23 11:11:33

标签: php mysql

我是PHP的新手,所以我遇到了一个问题,我在MySQL中获得了这些行

+---+--------------+
|ID |  published   |
+---+--------------+
| 1 |    TRUE      |
| 2 |    FALSE     |
| 3 |    TRUE      |
+---+--------------+

例如,我想更新ID号。 2使用复选框进入“TRUE”:

<?php 

$host="localhost";  
$username="root";  
$password="password"; // Mysql password 
$db_name="test"; // Database name 
$tbl_name="chek_box_test"; // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
?>

<?php 

$id = $_GET['id'];
$select = mysql_query("SELECT * FROM $tbl_name WHERE id = $id");
while($row = mysql_fetch_array($select)){
?>
<form method="post" action="checkbox_test.php?id=<?php echo $id; ?>">
<input type="checkbox" name="publish" <?php
if($row['publish'] == TRUE){
     echo "checked='checked'";
}
?>
/>
<input type='hidden' name='id' value="<?php echo $row['id']; ?>" />
<input type="submit" name="submit" value="Update"></form><?php } ?>

<?php 
if(isset($_POST['submit'])){
    echo $publish = ($_POST['publish'] == 1) ? TRUE : FALSE;
    $id=$_POST['id'];
    $query = mysql_query("UPDATE $tbl_name SET publish = '$publish' WHERE id =$id");
}
?>

我的问题是,如果我检查PHP它只给我'FALSE'值。我希望如果我检查并点击提交,它会给我“TRUE”或“FALSE”。

请帮我这样做。任何有用的建议将不胜感激。

2 个答案:

答案 0 :(得分:1)

缺少输入字段的值:

<input type="checkbox" name="publish" value="1" <?php
if($row['publish'] == 'yes'){
     echo "checked='checked'";
}
?>
/>

要解决错误'未定义的索引发布',您可以更改

echo $publish = ($_POST['publish'] == 1) ? TRUE : FALSE;

为:

$publish = FALSE;
if(isset($_POST['publish']) and $_POST['publish']==1) {
  $publish = TRUE;
}

答案 1 :(得分:0)

提及值=&#34; TRUE&#34;

   <input type="checkbox" name="publish"  <?php
   if($row['publish'] == 'yes'){
    echo "checked='checked' ";
    echo "value='TRUE'";
   }
   ?>
   />