使用复选框在mysql表中将值从0更新为1

时间:2013-09-22 11:12:17

标签: php mysql

MYSQL表结构

Name    Type            Collation         Attributes    Null    Default
code    varchar(2)      utf8_unicode_ci                  No     
name    varchar(255)    utf8_unicode_ci                  No     
checkbox  tinyint(1)                                     Yes       NULL

PHP

$countryiso = mysql_query("SELECT distinct name as name FROM location_country where code NOT IN('A1','A2','AP','EU') order by name");
echo '<table>';
echo '<th>Country</th><th> Add/Remove </th>';
while ($row = mysql_fetch_assoc($countryiso)) {
 echo '<tr>';
 echo '<td>'. $row['name'] . '</td>';
 echo '<td><input type="checkbox"></td>';
 echo '</tr>';
}
 echo '</table>';

当我检查我的php后端中的复选框时,我需要将列复选框中的值从0更新为1。我怎么用ph​​p和mysql这样做?请不要Jquery。

1 个答案:

答案 0 :(得分:2)

如果您不想使用JavaScript,则需要在表单末尾使用SUBMIT按钮:

$countryiso = mysql_query("SELECT distinct name as name FROM location_country where code NOT IN('A1','A2','AP','EU') order by name");
echo '<form action="" method="post">';
echo '<table>';
echo '<th>Country</th><th> Add/Remove </th>';
while ($row = mysql_fetch_assoc($countryiso)) {
 echo '<tr>';
 echo '<td>'. $row['name'] . '</td>';
 echo '<td><input type="checkbox" name="check[]" value="' . $row['code'] . '"></td>';
 echo '</tr>';
}
 echo '<tr><td>&nbsp;</td><td><input type="submit"></td></tr>';
 echo '</table>';
 echo '</form>';

然后:

if(isSet($_POST['check']) && $_POST['check'])
{
    foreach($_POST['check'] as $check)
    {
        mysql_query("UPDATE yourtable SET checkbox = 1 WHERE code = '" . mysql_real_escape_string($check) . "'");
        // any message of success
    }
}

但是不要忘记将来不推荐使用 mysql _ 。使用 PDO mysqli _