Gazeta Almedicus
Gazeta Almedicus

Reputation: 52

Checkbox values into mysql query

i have this code which permits me to retrieve data from a checkbox, there isn't any mysql included yet, so can you help me modify this?

The form is like this:

<form action="checkbox.php" method="post">
<input type="checkbox" name="checkbox[]" value="hostess_name">
<input type="checkbox" name="checkbox[]" value="hostess_familyname_en">
<input type="checkbox" name="checkbox[]" value="hostess_id">
<input type="checkbox" name="checkbox[]" value="hostess_firstname_en">
<br>
<br>
<input type="submit" name="Submit" value="Submit">
</form>

The values i inserted are supposed to be database fields, then i have this checkbox.php file which reads the values selected.

    <?php
mysql_connect("localhost", "root", "") or die(mysql_error());
echo "Connected to MySQL<br />";
?>
<?

/* and in your checkbox.php you do this: */

if(isset($_POST['Submit']))
{
echo "<pre>"; print_r($_POST);
}
$checked = mysql_real_escape_string(implode(',', $_POST['checkbox'])); 
echo $checked;
?>

How can assign to checkbox values database fields? What i'm trying to do is to store the values and export them into a query using implode.. Help me..

Upvotes: 1

Views: 2199

Answers (2)

Luke Pittman
Luke Pittman

Reputation: 843

Your POST variable ($_POST['checkbox']) is actually already an array. First, to figure out what you are actually working with, do this:

echo '<pre>';
print_r ($_POST['checkbox']);
echo '</pre>';

Then view your script and have a look at the output. Chances are you'll see an array with some keys and values. Using that you can decide how to proceed.

If it were me I would do something like the following to accomplish your task:

$sql = "SELECT `table_id_column`, `another_column` ";
foreach ($_POST['checkbox'] as $key => $value) {
  $sql .= ", `$value`";
}
$sql .= " FROM `hostess` ORDER BY `another_colmn` ASC";

Please keep in mind that allowing an SQL statement to be modified in this manner is very bad practice. You'll want to introduce some security into this before putting it on a production environment.

Luke

Upvotes: 2

arijeet
arijeet

Reputation: 1874

Use

foreach($_POST[checkbox] as $key => $value {
    echo PHP_EOL . "Key is => " . $key . " Value is => " . $value . PHP_EOL;
}

Try this and see the output, you'll see yourself how to proceed further.

Upvotes: 1

Related Questions