Viewed   248 times

everyone.

I know this is a far treated subject, but I've looked everywhere and cannot get it solved.

I have a series of checkboxes in my webpage and need to insert the values into a database.

For what I've read, it's supposed to be done this way:

<tr>
        <td class="titulofila">Sal&oacute;n Completo con: </td>
        <td>
        <table width="100%"><tr><td>
            <label>
            <input name="equipSalon[]" type="checkbox" id="equipSalon[]" value="mesa"  />
            mesas </label>
        </td><td>
            <label>
            <input name="equipSalon[]" type="checkbox" id="equipSalon[]" value="sillas"  />
            sillas </label>
        </td><td>
            <label>
            <input name="equipSalon[]" type="checkbox" id="equipSalon[]" value="sofa"  />
            sof&aacute;</label>
        </td></tr></table>
        </td>
    </tr>

And then, in the PHP script that the submit button takes to:

 $equipSalonF=mysql_real_escape_string(implode(',', $_POST['equipSalon']));
mysql_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']}'",$link);

I have more than this checkboxes and this doesn't work, just says "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 21"

If anyone wants to look at the full index.html and php files, you can have them here: http://paste.ideaslabs.com/show/8qEHDnsZdr the form starts at line 147. And the PHP File in here: http://paste.ideaslabs.com/show/IJFLSHM7Ka

Thanks in advance.

 Answers

1

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).

Tuesday, December 6, 2022
 
helios
 
5

I find this part a bit weird:

if (is_numeric($_POST['video']) && $_POST['video'] <2 )
{
    $video1 = isset($_POST['video']) ? '1' : '0';

You first check if it is numeric and then check if it is set. If it wasn't set, that if would become false automatically. In other words, $video is always 1. Assuming $video can be only true/false (or maybe it comes as "checked"/"unchecked", not really sure), use it like this:

$video1 = ($video ? '1' : '0');

Hopefully I spotted the issue successfully :)

UPDATE

<input type="checkbox" name="video" id="video" value="video" <?php
if($video == '1'){
     echo "checked='checked'";
}
echo "/>";

...

if (isset($_POST['submit']))
{
    echo $_POST['video']; // again, please tell what it outputs here!!!
    $video1 = (($_POST['video'] == "video") ? '1' : '0');
Friday, November 4, 2022
 
3

Name your form in html as -

<form id="prices_form" name="pricesForm" method="post" action=""> 

Try JSON.stringify() data before sending with the AJAX like below -

var data = JSON.stringify({ 
    action: 'ajaxsavePrice', 
    location1: $('#location1').val(), 
    location2: $('#location2').val(), 
    price: $('#price').val() 
});

And then replace your ajax call on form submit as below-

$('form.pricesForm').on('submit', function(e){
  e.preventDefault();
  $.ajax({
   method: 'POST',
   dataType: 'json',
   url: ajax_savePrice_object.ajaxurl, // also check this if it returns the correct url
   data: data,
   success: function(res){
     $('#prices_form').hide();
   }
  });

});

Hope this helps.

Monday, October 10, 2022
 
3

Create this php code

<?php
mysql_connect('localhost', 'username', 'password');
mysql_select_db('myTable');
$val = array();
if (isset($_POST['A']))
    $val[] = $_POST['A'];
if (isset($_POST['B']))
    $val[] = $_POST['B'];
if (isset($_POST['C']))
    $val[] = $_POST['C'];
$value = implode(', ', $val);
if (isset($_POST['select'])) {
    $col = $_POST['select'];
    if ($col == 'Category 1') {
        $query = mysql_query('INSERT INTO myTable(cat1) VALUES($value)');
    }
    else if ($col == 'Category 2') {
        $query = mysql_query('INSERT INTO myTable(cat2) VALUES($value)');
    }
    else if ($col == 'Category 3') {
        $query = mysql_query('INSERT INTO myTable(cat3) VALUES($value)');
    }
}
?>
Wednesday, December 21, 2022
 
4

Let me clearify you in an easy way...

This will be your controller

class Site extends CI_Controller
{
function index()
{
$this->load->view('form.php');// loading form view
}

function insert_to_db()
{
$this->load->model('site_model');
$this->site_model->insert_to_db();
$this->load->view('success');//loading success view
}
}

This will be your views. Befor creating views go to autoload.php and autoload url helper and database class. In your config.php set config['base_url'] = "path to your site"; form.php

<form action="<?php echo base_url();?>index.php/site/insert_into_db" method="post">
Field 1 = <input type = 'text' name='f1'>
Field 2 = <input type = 'text' name='f2'>
Field 3 = <input type = 'text' name='f3'>
<input type='submit'>
</form>

success.php

<b>Your data has been inserted!!!</b>

In your model you need to pull those datas of form and insert into db this way

site_model.php

class Site_model extends CI_Model
{
function insert_into_db()
{
$f1 = $_POST['f1'];
$f2 = $_POST['f2'];
$f3 = $_POST['f3'];
$this->db->query("INSERT INTO tbl_name VALUES('$f1','$f2','$f3')");
}
}

In this case your database has three fields... modify query as per your requirements

Tuesday, November 29, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :