且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP:将多个复选框值插入一个MySQL列

更新时间:2022-12-11 21:28:12

试试这整个例子,

表结构

CREATE TABLE IF NOT EXISTS `games` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `game_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;



<?php
include_once("yourconfig.php"); //include your db config file
extract($_POST);
$check_exist_qry="select * from games";
$run_qry=mysql_query($check_exist_qry);
$total_found=mysql_num_rows($run_qry);
if($total_found >0)
{
    $my_value=mysql_fetch_assoc($run_qry);
    $my_stored_game=explode(',',$my_value['game_name']);
}

if(isset($submit))
{
    $all_game_value = implode(",",$_POST['games']);
    if($total_found >0)
    {
        //update
        $upd_qry="UPDATE games SET game_name='".$all_game_value."'";
        mysql_query($upd_qry);

    }
    else
    {
        //insert
        $ins_qry="INSERT INTO games(game_name) VALUES('".$all_game_value."')";
        mysql_query($ins_qry);
    }
}

?>
<form method="post" action="">
Games You Like: <br/>
    <input type="checkbox" name="games[]" value="1" <?php if(in_array(1,$my_stored_game)){echo "checked";}?>><label>Football</label><br>
    <input type="checkbox" name="games[]" value="2" <?php if(in_array(2,$my_stored_game)){echo "checked";}?>><label>Basket Ball</label><br>
    <input type="checkbox" name="games[]" value="3" <?php if(in_array(3,$my_stored_game)){echo "checked";}?>><label>Pool</label><br>
    <input type="checkbox" name="games[]" value="4" <?php if(in_array(4,$my_stored_game)){echo "checked";}?>><label>Rugby</label><br>
    <input type="checkbox" name="games[]" value="5" <?php if(in_array(5,$my_stored_game)){echo "checked";}?>><label>Tennis</label><br>
    <input type="checkbox" name="games[]" value="6" <?php if(in_array(6,$my_stored_game)){echo "checked";}?>><label>Cricket</label><br>
    <input type="checkbox" name="games[]" value="7" <?php if(in_array(7,$my_stored_game)){echo "checked";}?>><label>Table Tennis</label><br>
    <input type="checkbox" name="games[]" value="8" <?php if(in_array(8,$my_stored_game)){echo "checked";}?>><label>Hockey</label><br>
    <input type="submit" name="submit" value="submit">
</form>

这只是我在这个例子中添加的基本示例和查询,您可以从这个基本示例中学习,我认为这对您非常有用...如果对此解决方案给出正确答案有用

this is just basic example and query i have added in this example, you can learn from this basic example and i think this is very useful for you... if useful than give correct answer for this solution