MySQL and PHP multiple checklist db insert - php

I am trying to insert the value of this multiple checklist into the db column. This code not working. Can anyone spot the problem?
My database consists of a table called "colors" and one column called "color".
<?php
// connect to database
require "mysql_connect.php";
?>
<?php
// get value from the form
$color = $_POST['color'];
foreach($_POST['color'] as $colors){
$insert = mysql_query("INSERT INTO colors (color) VALUES ('$color')");
}
?>
<form action="add_color.php" method="post" enctype="multipart/form-data" name="colorform" id="colorform">
<input type="checkbox" name="color[]" value="black" /> Black
<input type="checkbox" name="color[]" value="red" /> Red
<input type="checkbox" name="color[]" value="blue" /> Blue
<input type="checkbox" name="color[]" value="white" /> White
<input name="submit" type="submit" value="Add color" />
</form>
Thanks

This is a nice way to add your colors
<?php
require "mysql_connect.php";
// connect to database
$colors=array();
// get value from the form
if (isset($_POST['color'])) $colors = $_POST['color'];
foreach($colors as $color)
{
mysql_query ("INSERT INTO colors ('color') VALUES ('$color')");
}
?>
<form action="add_color.php" method="post" enctype="multipart/form-data" name="colorform" id="colorform">
<input type="checkbox" name="color[]" value="black" /> Black
<input type="checkbox" name="color[]" value="red" /> Red
<input type="checkbox" name="color[]" value="blue" /> Blue
<input type="checkbox" name="color[]" value="white" /> White
<td><input name="submit" type="submit" value="Add color" />
</form>
if (isset($_POST['color']))
This condition is important because it will prevent an indexing error in case the array is empty
$colors=array();
Also, do declare your variables to prevent getting undeclared varibles, previously, in your code, this will happen if the user does not specify any color
Remember PHP is server-side and thus getting errors on PHP create loopholes for attacks. Try to read about PHP Best Practices, Its very impotant
Hopes it helps :-)

I would also suggest that you sanitize your from inputs before inserting into your database. You don't mention what type your color column is, could be a mismatch there as well.
When you say INSERT INTO $colors -- is that what you mean? Your table name is variable? You should probably have a proper table name in place of $colors.
In addition, you have used $color which I don't see defined, you probably meant to use $colors so it should be more like this:
INSERT INTO tblColors (color) VALUES ('$colors')
To check your return value to see what error you're getting:
$query = "INSERT INTO tblColors (color) VALUES ('$colors')";
$insert = mysql_query($query) or die("A MySQL error has occurred.<br />Your Query: " . $query . "<br /> Error: (" . mysql_errno() . ") " . mysql_error());

$insert = mysql_query("INSERT INTO $colors (color) VALUES ($color)");
Change it to:
$insert = mysql_query("INSERT INTO colors_table_name (color) VALUES ($color)");
Also, please check the return value of insert, maybe you are getting errors?
First obvious problem was that the table name was being replaced with the color because of the variable, is this the desired effect?

<?php
// connect to database
require "mysql_connect.php";
?>
<?php
// get value from the form
$colors = $_POST['color'];
foreach($colors as $color){
$insert = mysql_query("INSERT INTO colors (color) VALUES ($color)");
}
<form action="add_color.php" method="post" enctype="multipart/form-data" name="colorform" id="colorform">
<input type="checkbox" name="color[]" value="black" /> Black
<input type="checkbox" name="color[]" value="red" /> Red
<input type="checkbox" name="color[]" value="blue" /> Blue
<input type="checkbox" name="color[]" value="white" /> White
<td><input name="submit" type="submit" value="Add color" />
</form>

You've got your variables backwards, SQL syntax errors, SQL injection vulnerabilities, and a total lack of error handling
$color = $_POST['color']; <---stuff the POST data array into $color
foreach($_POST['color'] as $colors){ <--- loop over the POST data directly
$insert = mysql_query("INSERT INTO colors (color) VALUES ($color)");
^^^^^^---insert the array
^^^^^^---no quotes
You use $colors (with an S) to store the individual colors, but then insert $color, which is an array.
Never assume that a query has suceeded. If you'd have the bare minimum or die(...) error handling, you've have seen why your queries were failing:
foreach($_POST['color'] as $color) {
$safe_color = mysql_real_escape_string($color);
$result = mysql_query("INSERT INTO colors (color) VALUES ('$safe_color');") or die(mysql_error());
}

Related

how do i select multiple mysql records based on checked checkboxes?

on page 1 i have a form, then on page 2 which is the processor file, i want to select records based on the checked checkboxes that were checked on page 1.
<form action="output.php" method="post">
<input type="checkbox" id="" class="" name="check_list[]" value="something" />
<input type="checkbox" id="" class="" name="check_list[]" value="something else" />
<input type="checkbox" id="" class="" name="check_list[]" value="yet another thing" />
<input type="checkbox" id="" class="" name="check_list[]" value="one more thing" />
<input type="checkbox" id="" class="" name="check_list[]" value="some name" />
<input type="checkbox" id="" class="" name="check_list[]" value="some other name" />
<input type="submit" value="Submit" name="submit">
</form>
the following foreach can display all the values of everything that was checked, but i don't know how to take it further into my sql select statement to select all the records that have a column field by that name.
foreach($_POST['check_list'] as $check) {
echo $check . '<br>';
}
lets say in a table called stuff there are these fields
id, first_title, second_title
so i want to do the following, but obviously this isn't the way to write it. this is the part i need help with.
SELECT * FROM stuff WHERE first_title = $check or second_title = $check
lets us further say that these records exist in the table...
id first_title second_title
-----------------------------------------
1 something something else
2 yet another thing one more thing
3 some name some other name
then lets say these checkboxes were checked:
<input type="checkbox" id="" class="" name="check_list[]" value="something" />
<input type="checkbox" id="" class="" name="check_list[]" value="one more thing" />
so what i want to happen is for my select statement to select record 1 and record 2 and not record 3, because "something" is in the first_title column of the first record, and "one more thing" is in the second_title of the second record, and nothing was checked that is in third record.
i hope i gave as much detail as is needed. let me know if you need further explanation.
Use the SQL IN operator to test if a column is in a list of values. Here's how to write it with MySQLI:
$in_str = implode(', ', array_map(function($title) use ($con) {
return "'" . $con->real_escape_string($title) . "'";
}, $_POST['check_list']));
$sql = "SELECT * FROM stuff WHERE first_title IN ($in_str) OR second_title IN ($in_str)";
$result = $con->query($sql);
try this dynamic where condition in your code
<?php
$arr_where = array();
foreach($_POST['check_list'] as $check) {
$arr_where[] = " first_name='$check' OR last_name='$check' ";
}
$where_text = implode("OR", $arr_where);
$sql = "SELECT * FROM stuff WHERE ".$where_text;
?>

Search All items from select box in php code

I have form and php file, and I need to query color in array data from database.
data looks like
red,white mustang 1977
black,blue ford 2000
white,pink,blue opel 2003
and form looks like
<form method="POST" action="select.php">
<p><input type="radio" value="just" checked name="selection">just selected<input type="radio" name="selection" value="allinclude">all include </p>
<p><input type="checkbox" name="color[]" value="ON">red</p>
<p><input type="checkbox" name="color[]" value="ON">blue</p>
<p><input type="checkbox" name="color[]" value="ON">black</p>
<p><input type="checkbox" name="color[]" value="ON">white</p>
<p><input type="checkbox" name="color[]" value="ON">pink</p>
<p> </p>
<p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>
and I need 2 sql query, one of check all selected options together in data, and one of any of them in data
in my select.php
$selection= $_POST["selection"];
$color=implode(",",$_POST["color"]);
$sql= mysql_query("select model,year,color where color like '%".$color."%'");
When I select blue and white, sql returns no row.
If I select white, then returns 2 row
But I want to select all include radio box and select blue and white then return 3 rows
How can I write second sql for all included selection?
Here is new codes, but this is only query latest item in array, not all selected for 'just' section of selection form
$selection= $_POST["selection"];
$color=implode(",",$_POST["color"]);
if($selection=='just'){
$colorselect = explode(',', $color);
foreach($colorselect as $b)
{
$mycolor = trim($b);
$sql= mysql_query("select model,year,color where color like '%".$mycolor."%'");
}
}
else{
$sql= mysql_query("select model,year,color where color like '%".$color."%'");
}
If I understand your problem correctly, your first query gets all rows that include all of the colors selected - and you need a second query that will get all rows that include just one or more of the colors selected. In that case, you need your query to include a series of ORs that will check for each individual color in each row. (Note: your query seems to be missing a FROM statement. I have added this in, assuming your table is called cars).
Assuming $colors is an array of selected colors, eg: ['blue', 'white', 'red'], you could set up your query as follows:
$query = 'SELECT model,year,color FROM cars WHERE ';
$or = '';
foreach ($colors as $color) {
$query .= $or . "color LIKE '%" . $color . "%'";
$or = ' OR ';
}
This will effectively build a query that looks like this:
SELECT model,year,color
FROM cars
WHERE color LIKE '%blue%'
OR color LIKE '%white%'
OR color LIKE '%red%'
which will select all the rows from your example data - each row contains at least one of the colors selected. If you wanted to change this logic to get all rows that include all of the colors, simply change OR to AND - this will match rows that have all selected colors, regardless of the order in which they were selected.
Additional thoughts:
Storing comma separated values like blue,white is usually bad practice. Consider normalizing your data and use a system that includes something like a colors and car_colors table.
mysql_* functions are deprecated. Consider switching to mysqli_* or pdo
UPDATE:
Here is the complete system. This will create the appropriate query based on which radio button is selected:
(Assuming the sample data you provided is in a table called cars)
form:
<form method="POST" action="select.php">
<p><input type="radio" value="just" checked name="selection">just selected<input type="radio" name="selection" value="allinclude">all include </p>
<p><input type="checkbox" name="color[]" value="red">red</p>
<p><input type="checkbox" name="color[]" value="blue">blue</p>
<p><input type="checkbox" name="color[]" value="black">black</p>
<p><input type="checkbox" name="color[]" value="white">white</p>
<p><input type="checkbox" name="color[]" value="pink">pink</p>
<p> </p>
<p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>
select.php:
$selection = $_POST['selection'];
$colors = $_POST['color'];
$op = $selection == 'just' ? ' AND ' : ' OR ';
$query = 'SELECT model,year,color FROM cars WHERE ';
$and_or = '';
foreach ($colors as $color) {
$query .= $and_or . "color LIKE '%" . $color . "%'";
$and_or = $op;
}
$sql = mysql_query($query);
The effective HTML of Fred -ii-s comment is:
<form method="POST" action="select.php">
<p><input type="radio" value="just" checked name="selection">just selected<input type="radio" name="selection" value="allinclude">all include </p>
<p><input type="checkbox" name="colors[]" value="red">red</p>
<p><input type="checkbox" name="colors[]" value="blue">blue</p>
<p><input type="checkbox" name="colors[]" value="black">black</p>
<p><input type="checkbox" name="colors[]" value="white">white</p>
<p><input type="checkbox" name="colors[]" value="pink">pink</p>
<p> </p>
<p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>
And then in your PHP code you would just use the $_POST['colors'] array of data like any other array in PHP.
$colors = implode($_POST['colors'],',');
$sql= mysql_query("select model,year,color where color in (".$colors.")");
Your HTML:
<form method="POST" action="select.php">
<p><input type="radio" value="just" checked name="selection">just selected<input type="radio" name="selection" value="allinclude">all include </p>
<p><input type="checkbox" name="color[]" value="red">red</p>
<p><input type="checkbox" name="color[]" value="blue">blue</p>
<p><input type="checkbox" name="color[]" value="black">black</p>
<p><input type="checkbox" name="color[]" value="white">white</p>
<p><input type="checkbox" name="color[]" value="pink">pink</p>
<p> </p>
<p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>
Your PHP:
$colors = array("red", "blue", "black", "white", "pink");
// Make sure that only allowed colors make through - we don't want SQL injection
$selection = array();
foreach ($_POST["colors"] as $color)
{
if (in_array($color, $colors) === true)
{
$selection[] = $color;
}
}
// Now a bit of magic
$sql= mysql_query("select model,year,color from data where color like '%" . implode("%' " . ($_POST["selection"] === "just" ? "or" : "and") . " color like '%",$selection) . "%'");

store multiple checkbox values to database using php and mysql

I want to store the multiple checkbox values to store in a single field. I use that link http://www.mindfiresolutions.com/Storing-array-data-to-MySQL-using-PHP-1296.php. But i dont get the result.Give Help to find that problem.
Set your column as 'set' (specify the all possible values.) data type and than run the below query.
$comma_separated = implode(",", $values);
$insert_query = "INSERT INTO TABLE_NAME(col_name) VALUES('$comma_separated')";
$result_insert = mysql_query($insert_query);
I hope this will solve your problem.
I hope this will helpful
<html>
<body>
<form action="" method="post">
<p><input type="checkbox" name="color[]" value="red" />Red</p>
<p><input type="checkbox" name="color[]" value="blue" />Blue</p>
<p><input type="checkbox" name="color[]" value="orange" />orange</p>
<input type="submit" value="submit" name="sub" />
</form>
<?php
if(isset($_POST['sub']))
{
mysql_connect("localhost","root","") or die("Server Could not be connected");
mysql_select_db("gobinath") or die("database connection problam");
$color=implode(',',$_POST['color']);
mysql_query("insert into mcheck values('','$color')") or die("insert problam");
}
?>
</body>
</html>

Carrying a checkbox selection in a session

How do I wrap the selections in a session that can be carried over multiple pages?
This is what I have:
session_start();
<form action="checkbox-form.php" method="post">
Select your options<br />
<input type="checkbox" name="options[]" value="A" />A<br />
<input type="checkbox" name="options[]" value="B" />B<br />
<input type="checkbox" name="options[]" value="C" />C<br />
<input type="submit" name="formSubmit" value="Submit" />
</form>
var_dump($_POST['options']);
foreach($_POST['options'] as &$option){
mysql_real_escape_string($option);
}
$insert = "INSERT INTO submitted (statuses)
VALUES ('". implode(",", $_POST['options']) ."')";
$query = mysql_query($insert) or die ("Error: ".mysql_error());
So, how do I put $_POST['options']; in a session. I tried doing
$_SESSION['options'] = mysql_real_escape_string($_SESSION['options']);
When i do that i get "array" as the result.
You are storing a array in session variable and complaining that its returning me a array!!!
Of course it will return an array...to access a particular key of the same use..
$_SESSION['options'][0]
$_SESSION['options'][1]
$_SESSION['options'][2]
which consecutively correspond to your A,B,C checkboxes on the form...
simply do it
session_start();
$_SESSION['options'] = $_POST['options'];
and you can access checkbox value by
$_SESSION['options'][$i] where $i <count($_SESSION['options'])

combine checkbox values using php mysql

I having around 20 check boxes in my form as
<input type="checkbox" name="c1" value="1" />
<input type="checkbox" name="c2" value="2" />
<input type="checkbox" name="c3" value="3" />
<input type="checkbox" name="c4" value="4" />
i would like to these values to a database. I just thought rather than creating 20 fields in my database grab all the values at store in the db as 1,2,3,4 and then when querying to explode the values and display it accordingly using php.
can someone please tell me how am i supposed to concatenate the values 1,2,3,4 from the check fields when submitted so i can pass to the database.
i would appreciate if anyone can suggest a different effective way to achieve this using php.
You can change the name of the checkboxes to be the same, something like
<input type="checkbox" name="cb[]" value="1" />
<input type="checkbox" name="cb[]" value="2" />
Then access them via $_GET or $_POST via
if (isset($_POST['cb'])) {
$my_values = implode(",", $_POST['cb']);
}
If you want them sorted, then you will want to do something like this:
if (isset($_POST['cb'])) {
$my_values = $_POST['cb'];
sort($my_values);
$my_db_value = implode(',', $my_values);
}
For the record, I agree with #Shef in the case that the database can handle the extra load. Depending on when this information will be needed in a highly scalable solution, however, this is a perfectly acceptable way to handle this.
To answer your initial question, first off you need to name your checkboxes all the same name, so:
<input type="checkbox" name="box[]" value="1" />
....
<input type="checkbox" name="box[]" value="20" />
PHP script:
$boxes = $_POST['box'];
$values = implode(",", $boxes); // $values now has "1,2,3,4...", insert into table
A better way would be to have a separate table (see #Shef 's comment).

Categories