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) . "%'");
Related
I have searched everywhere and still cannot find the answer. Can anybody help?
I have a PHP form that consists of a textbox (with data that will go into column name_id) and a checkbox, that has the option to go to 5 different MySQL tables:
'table A'
'table B'
'table C'
'table D'
'table E'
People can choose which table they want, and the name_id will go to the tables selected.
How can I do this?
my Answere in different from #RandD-SexyBoy- . my sql query is different from #RandD-SexyBoy- he has used $sql = "INSERT INTO $tables[$i](nameID_column); with out VALUES (:nameID_column)
were is have used $sql->prepare("INSERT INTO ".$v." (name_id) VALUES (?)"
Here are 3 cases the user responds
case first : user may select a single table
case second : user may select multiple tables. here we must use foreach() loop and dynamic sql queries.
case third : user may not select any table in this case we must give user a message table not selected
html form :
`
<html>
<head>
</head>
<body>
<form action="" method="post">
<input type="text" name="name_id" required>
<p>select your table to add data</p>
<input type="checkbox" name="tables[]" value="tblA">Table A<br>
<input type="checkbox" name="tables[]" value="tblB">Table B<br>
<input type="checkbox" name="tables[]" value="tblC">Table C<br>
<input type="checkbox" name="tables[]" value="tblD">Table D<br>
<input type="checkbox" name="tables[]" value="tblE">Table E<br>
<input type="submit" name="submit">
</form>
</body>
</html>
`
php file :
<?php
$con = new mysqli('localhost','root','admin','demo');
if(!$con){
die("Connection ".$con->connect_error);
}
if(isset($_POST['submit'])){
$name_id = $_POST['name_id'];
$tables = $_POST['tables'];
if(!empty($tables)){
foreach($tables as $key=>$v){
$sql = $con->stmt_init();
if($sql->prepare("INSERT INTO ".$v." (name_id) VALUES (?)")){
$sql->bind_param($name_id);
$sql->execute();
echo "DATA INSERTED";
}
else
{
echo "Error".$con->error;
}
}
}
else
{
echo "You have not selected tables";
}
}
?>
So one naive approach could be, when the user submits the form, on your php side, you check which checkboxes are ticked and your condition could be something like this
if(checkbox_for_table_A) {// insert query}
if(checkbox_for_table_B) {// insert query}
if(checkbox_for_table_C) {// insert query}
if(checkbox_for_table_D) {// insert query}
if(checkbox_for_table_E) {// insert query}
This way if one checkbox is selected it will save into that table, if more than one tables are selected, it will go in that table.
Hope this helps! Ask any doubt you get in the comment section.
Adapting from sources : post checkbox value and tutorial http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-pdo/, you can use this approach :
HTML Form :
<form action="checkbox-form.php" method="post">
<input type="text" name="name_id" /><br />
Select your database: <br/>
<input type="checkbox" name="formTables[]" value="A" />Table A<br />
<input type="checkbox" name="formTables[]" value="B" />Table B<br />
<input type="checkbox" name="formTables[]" value="C" />Table C<br />
<input type="checkbox" name="formTables[]" value="D" />Table D<br />
<input type="checkbox" name="formTables[]" value="E" />Table E<br />
<input type="submit" name="formSubmit" value="Submit" />
</form>
Now the PHP script :
<?php
$pdo_connection = new PDO('mysql:host=localhost;dbname=test', 'demouser', 'demopass');
$tables = $_POST['formTables'];
if(empty($tables))
{
echo("You didn't select any tables.");
}
else
{
$N = count($tables);
echo("You selected $N table(s): ");
for($i=0; $i < $N; $i++)
{
$sql = "INSERT INTO $tables[$i](nameID_column);
$stmt = $pdo_connection->prepare($sql);
$stmt->bindParam(':nameID_column', $_POST['name_id'], PDO::PARAM_STR);
$stmt->execute();
echo("Your ID Name was inserted into table $tables[$i] ! <br /> ");
}
}
?>
how to save multiple radio button in database using php without save button value.
my code :
$user_id = $_POST['user_id'];
foreach ( $_POST as $key => $val ) {
if ($key <> 'user_id') {
$bidder_interst_insert="INSERT INTO bidder_interest_list(id, bidder_id, bidder_interest_name) VALUES ('','$user_id','$val')";
$bidder_interst_insert_result = mysql_query($bidder_interst_insert);
if (mysql_affected_rows() > 0) {
$interest_list_success = "Thank you Successfull insert your interst list.";
$_SESSION['interest_list_success_msg'] = $interest_list_success;
} else {
$insert_error = "interst list Insert Error.";
$_SESSION['insert_error_msg'] = $insert_error;
header("location:interest_list.php");
}
}
}
This code work but database extra save in save button value how to solved this problem??
foreach ( $_POST as $key => $val ){
You are directly looping the $_POST, so the SAVE button value is also saving in the database. Take the values individually instead of looping the whole $_POST, then the SAVE button value won't be saved in the database.
And moreover you are using mysql functions which are deprecated, use mysqli or PDO.
EDIT::
Just take it the same way as u took user_id ==> $variablename = $_POST['fieldname'];
EDIT:::
Let me suppose i have a form like this
<form name="form1" id="form1" method="post" action="">
<input type="checkbox" name="products[]" value="A" checked="checked" />A <br />
<input type="checkbox" name="products[]" value="B" checked="checked" />B <br />
<input type="checkbox" name="products[]" value="C" checked="checked" />C <br />
<input type="checkbox" name="products[]" value="D" checked="checked" />D <br />
<input type="checkbox" name="products[]" value="E" checked="checked" />E <br />
<input type="checkbox" name="products[]" value="F" checked="checked" />F <br />
<input type="submit" name="save" id="save" value="Save" />
</form>
then i can do it like:
<?php
if(isset($_POST['save']))
{
$products = $_POST['products'];
foreach($products as $key => $value)
{
$qry = mysql_query("INSERT INTO tbl(product) VALUES('$value')");
}
}
?>
Try this
unset($_POST['name-of-save-button']);
$data = $_POST;
foreach ( $data as $key => $val ){//your code here}
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;
?>
I am trying to do eCommerce filtering on the category page. So far I can get it to work for one colour, but if the user checks more than one colour, I want it to search for the other colour too.
URL
//current
category.php?colourChoice=White
//more than one
category.php?colourChoice=White&colourChoice=Ruby+Red
I realise I need some sort of form array or an explode?
MYSQL
products
---
id sku price
1 p22 45.00
2 p33 65.00
3 p44 70.00
colours
---
id sku name
1 p22 White
2 p33 Ruby Red
3 p44 Black
HTML
<form action="form.php" method="get">
<input type="checkbox" name="colourChoice" value="White"/>
<input type="checkbox" name="colourChoice" value="Black"/>
<input type="checkbox" name="colourChoice" value="Ruby Red"/>
<input type="checkbox" name="colourChoice" value="Orange"/>
<input type="submit" value="go">
</form>
PHP
// VARS
$colourName=mysql_real_escape_string($_GET["colourChoice"]);
// MYSQL
$checkSQL=mysql_query("
SELECT * FROM `products`
INNER JOIN `colours`
ON `products`.`sku` = `colours`.`sku`
WHERE (
name = '".$colourName."'
OR name LIKE '".$colourName.";%'
OR name LIKE '%;".$colourName.";%'
OR name LIKE '%;".$colourName."'
)
");
// SHOW RESULTS
while($r = mysql_fetch_array($checkSQL)) {
echo '
<div class="product">
Cost £'.$r['price'].'<br />
</div>
';
}
You have to make checkbox array as below
<form action="form.php" method="get">
<input type="checkbox" name="colourChoice[]" value="White"/>
<input type="checkbox" name="colourChoice[]" value="Black"/>
<input type="checkbox" name="colourChoice[]" value="Ruby Red"/>
<input type="checkbox" name="colourChoice[]" value="Orange"/>
<input type="submit" value="go">
</form>
Then, you will get multiple value checked into array in php.
foreach($_GET["colourChoice"] as $value){
/// here you can make concat for where clause.
}
You can get HTML input values in PHP as array:
HTML
<form action="form.php" method="get">
<input type="checkbox" name="colourChoice[]" value="White"/>
<input type="checkbox" name="colourChoice[]" value="Black"/>
<input type="checkbox" name="colourChoice[]" value="Ruby Red"/>
<input type="checkbox" name="colourChoice[]" value="Orange"/>
<input type="submit" value="go">
</form>
Then you query the database using prepare/execute statements to prevent SQL injection.
PHP
$placeholders = substr(str_repeat('?, ', count($_GET['colourChoice']), 0, -1);
$query = "
SELECT * FROM `products`
INNER JOIN `colours`
ON `products`.`sku` = `colours`.`sku`
WHERE name in ($placeholders);
");
$db = new PDO(...);
$stmt = $db->prepare($query);
$stmt->execute($_GET['colourChoice']);
print_r($stmt->fetchAll());
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());
}