且构网

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

使用PHP将复选框值插入MySQL数据库

更新时间:2023-02-08 17:21:39

Checkboxes are only posted when they are ticked. So if the checkbox is not ticked, is will not appear in $_POST. Also you should generally not give any values to checkboxes. Instead use names to distinguish between them.

In the database I usually represent checkboxes with tinyints and store 1 for checked and 0 for unchecked.

// If your checkbox name is foo, this will convert it
// into a value that can be stored in the database
$foo = isset($_POST['foo']) ? 1 : 0;

Also note that html requires ids to be unique. So you can't have multiple elements with the same id. And you should sanitize your inputs to prevent sql injection. Use mysql_real_escape_string() on user inputs that go in the database.

Update

The main issue is that the query is missing a ')' at the last line. The query should look like

$query = "INSERT INTO markers (ciudad,
                        zona,address,name,
                        telefono,email,piso,
                        tipo,erasmus,nhabitaciones,
                        plazas,equipHabita,nbanos,
                        salon,cocina,electrodomesticos,
                        garaje,internet,calefaccion,
                        sexo,precio,superficie,otros,
                        fecha,lat,lng)
    VALUES ('{$_POST['ciudad']}','{$_POST['zona']}',
            '{$_POST['address']}','{$_POST['name']}','{$_POST['telefono']}',
            '{$_POST['email']}','{$_POST['piso']}','{$_POST['tipo']}',
            '{$_POST['erasmus']}','{$_POST['nhabitaciones']}',
            '{$_POST['plazas']}','{$equipHabitaF}',
            '{$_POST['nbanos']}','{$equipSalonF}',
            '{$equipCocinaF}','{$equipElectroF}','{$_POST['garaje']}',
            '{$_POST['internet']}','{$_POST['calefaccion']}',
            '{$_POST['sexo']}','{$_POST['precio']}',
            '{$_POST['superficie']}','{$_POST['otrosF']}',
            '{$_POST['fecha']}','{$_POST['lat']}',
            '{$_POST['lng']}')";
mysql_query($query, $link);

Note the closing ')' on the last line of the query. Also note that creating the query like this, in a variable, allows you to output the created query so you can see what exactly is sent to MySQL and you also can test your query in a different environment (ie in phpmyadmin or any other database administration tool).

上一篇 : :如何禁用和取消选中数据库字段中的复选框值.下一篇 : Codeigniter捕获数据库错误

相关阅读

技术问答最新文章