Using jQuery serialize to put ajax values into a database select query - php

I have the following code:
<?php
$allform = $_POST['allform'];
parse_str($allform, $output);
$allquery = "SELECT * FROM wp_users";
$names = array();
$allresult = mysql_query($allquery) or die(mysql_error()); ?>
...
<?php
while ($rows = mysql_fetch_array($allresult)) {
$names[] = $rows['user_email'];
}
?>
The allform variable is a jQuery serialize string:
var allform = $('form#all').serialize();
Basically, I want to put the values from the form in the front end into a mysql select query in the back end.
The form is a bunch of checkboxes so the idea is that the SELECT something will have different number of values depending on what the user checks. Any ideas?
Thanks

The best thing to do could be something like this. Your checkboxes should be like this
<input type="checkbox" name="checkboxes[]" value="cream" />
<input type="checkbox" name="checkboxes[]" value="choco" />
<input type="checkbox" name="checkboxes[]" value="lime" />
server side you receive an array
$flavours = $_POST["checkboxes"];
$sql = "SELECT ".implode(',', $flavours)." FROM FLAVOURTABLE";

Related

Checkboxes - print checked values in checkbox from database

In insert form I am using check boxes to insert values in database. Now, I want to get checked values in edit form so I can check new values or uncheck checked values.
First I get values from database (I am using pdo, I will not post connection code to db- it works):
get oprmea from database
$sql_oprema = "SELECT Oprema FROM dbo_emarketing_stavke_oprema WHERE Partner='$id'";
$n = $conn->query($sql_oprema);
while ($r = $n -> fetch()) {
$oprema_sql = $r['Oprema'];
}
I get values when I dump variables, output is not NULL.
I am using function to store values in database. Now I want to use same function for editing if posssible.
function emarketing_oprema(){
$link = new mysqli("localhost", "root", "le30mu09", "websoft");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT * FROM `dbo_emarketing_oprema` order by OpremaId asc ");
while($record = mysqli_fetch_array($sql)) {
echo '<input type="checkbox" name="oprema[]" value="'.$record['OpremaId']. '">' . $record['OpremaNaziv'] . ' <br/><br/> </input>';
}
}
I was wondering is it possible to use this function to get checked values checked.
use checked attribute
<input type="checkbox" checked>
or like this
<input type="checkbox" checked="checked">
You php will look like this:
while($record = mysqli_fetch_array($sql)) {
data='<input type="checkbox" name="oprema[]" value="'.$record["OpremaId"];
if(isset($record['checked'])) {//field in the database
data+=' checked="checked';
}
data+='">'. $record["OpremaNaziv"].'</br>';
}

how to search array of checkboxes

Im building a search form but how do you search a array of checkboxes?
here is my html form
<form method="get">
<label>
<input type="checkbox" name="material[]" value="metal">metal
</label>
<label>
<input type="checkbox" name="material[]" value="plastic">Plastic
</label>
<label>
<input type="checkbox" name="material[]" value="carbon">Carbon
</label>
<input type="text" name="keyword">
<input type="submit" value="search">
</form>
and the php so far is. So how can i search the material for each checked.
<?php
if(isset($_GET['keyword'])){
$keyword = $_GET['keyword'];
// $material = $_GET['material'];
// $Search->search($keyword);
}
?>
ANd the query would be so far
$query = $this->pdo->prepare('SELECT * FROM `shop` WHERE `material` = ?');
When posted this will submit an array named material (accessible via $_GET['material']) that contains only the values that were checked.
You can then use those or output them like this:
foreach ($_GET['material'] AS $material) {
echo $material;
}
Addition after the question was edited:
You can also implode() the array values with ', ' as glue and use that as the search parameter in your SQL statement. Just change it to use IN instead of =, like #Prashant M Bhavsar suggested in his answer.
I think this will help you
Get your submitted material array in variable
$material_array = $_POST['material'];
You can implode array in select query to fetch related result
$selected_search_material = implode(',', $material_array);
SELECT * FROM `shop` WHERE `material` IN ($selected_search_material)
I haven't tested this yet, but since you receive an array ($_get['material'] is already an array), just use the following code with find_in_set;
<?php
$materials = array();
if (array_key_exists('material', $_GET)) {
$materials = $_GET['material'];
}
$query = $this->pdo->prepare('SELECT * FROM `shop` WHERE find_in_set(cast(material as char), :materials');
$query->execute(array('materials' => $materials));
?>
Implode $_GET['material'] and use a different query:
$where = implode(', ',$_GET['material']);
$query = $this->pdo->prepare('SELECT * FROM `shop` WHERE `material` IN ?');
Then use $where in your execute();
You can use $materialValue to store into Database.
<?php
if(isset($_GET['material'])){
$material = $_GET['material'];
foreach($material as $materialIndex){
$materialValue .= $materialIndex.',';
}
}
// use value to store into db
pass $materialValue variable to IN query also remove last "," from string
$materialValue.substring(0,$materialValue.length()-1);
?>

multiple checkboxes used for search in php and mysql?

This seems to be a common question as I have seen plenty of similar questions.
however, none of the answers actually pointing out how to do the selecting from mysql database and this is my issue as the moment.
basically I have a table which I store the search data in it.
it looks like this:
id blond darkHair busty curvy
---------------------------------------------------
1 blond busty
2 dark hair busty curvy
3 blond curvy
4 blond curvy
and I have a form with checkboxes like so:
<form action="search.php" method="post">
<input name="keyword[]" type="checkbox" value="blond" />
<input name="keyword[]" type="checkbox" value="dark hair" />
<input name="keyword[]" type="checkbox" value="busty" />
<input name="keyword[]" type="checkbox" value="curvy" />
</form>
and the PHP codes like this:
if(isset($_POST['keyword']))
{
$keyword = $_POST['keyword'];
foreach ($_POST['keyword'] as $keyword) {
$keywordarray[] = mysqli_real_escape_string($conx, $keyword);
}
$keywords = implode (",", $keywordarray);
$sql = "SELECT * FROM girlsStaff
WHERE (`blond` LIKE '%".$keyword."%') OR (`darkHair` LIKE '%".$keyword."%') OR (`busty` LIKE '%".$keyword."%') OR (`thin` LIKE '%".$keyword."%')" or die();
$query = mysqli_query($conx, $sql);
Now, apart from converting this code to PDO or prepared statement, there is another issue which I don't understand!
it doesn't matter how many chechboxes i select... it always returns the result for last checked/selected checkbox value from mysql database....
is there something that I am missing?
i also, did echo $keywords at the top of my page to see whats being sent to the page and I get the value of all the selected/checked boxes being sent correctly.. so I know the issue is not there.
any help or advice would be appreciated.
You require to build query dynamically.
<?php
$clause = " WHERE ";//Initial clause
$sql="SELECT * FROM `girlsStaff` ";//Query stub
if(isset($_POST['submit'])){
if(isset($_POST['keyword'])){
foreach($_POST['keyword'] as $c){
if(!empty($c)){
$sql .= $clause."`".$c."` LIKE '%{$c}%'";
$clause = " OR ";//Change to OR after 1st WHERE
}
}
}
echo $sql;//Remove after testing
}
?>
<form method="POST" action="#">
<form action="search.php" method="post">
Blond: <input name="keyword[]" type="checkbox" value="blond" />
Dark Hair: <input name="keyword[]" type="checkbox" value="dark hair" />
Busty : <input name="keyword[]" type="checkbox" value="busty" />
Curvy; <input name="keyword[]" type="checkbox" value="curvy" />
<input type="submit" name="submit" value="Submit">
</form>
Sample queries
2 check boxes filled
SELECT * FROM `girlsStaff` WHERE `dark hair` LIKE '%dark hair%' OR `curvy` LIKE '%curvy%'
4 filled
SELECT * FROM `girlsStaff` WHERE `blond` LIKE '%blond%' OR `dark hair` LIKE '%dark hair%' OR `busty` LIKE '%busty%' OR `curvy` LIKE '%curvy%'
I think that small change from $keyword to $keywords will solve your problem :)
Now you are looking for items like your last value from $_POST['keyword'] array.
This line:
$sql = "SELECT * FROM girlsStaff WHERE (`blond` LIKE '%".$keyword."%') OR (`darkHair` LIKE '%".$keyword."%') OR (`busty` LIKE '%".$keyword."%') OR (`thin` LIKE '%".$keyword."%')" or die();
You should also use IN instead of LIKE if you have list aaa, bbb, ccc...., but then you will look for elements that have exactly same string in those fields.
After change to $keywords you will have:
... WHERE (`blond` LIKE '%".$keywords."%')
will also not work due to it will mean:
... WHERE (`blond` LIKE '%aaa,bbb,ccc%')
If you want to use like (if fields in DB only contain strings from array) then I suggest to build your query in foreach loop. Example:
$sql = "SELECT * FROM girlsStaff WHERE ".
foreach ($_POST['keyword'] as $keyword) {
$sql .= "(`blond` LIKE '%".$keyword."%') OR ";
}
//and here cut last four character " OR " part that will be unusefull
Typos:
$keywords = implode (",", $keywordarray);
^--- with an S
WHERE (`blond` LIKE '%".$keyword."%')
^--- without an S
You're stuffing in your original $_POST['keyword'] array. An array in string context is the literal word Array, so your query is actually executing as
WHERE (`blond` LIKE '%Array%')

put tick on checkbox based on database value

I'm updating some countries values into db table. All countries fetch from TBL_COUNTRY table. Then few countries store to another table. I'm using implode function to store multiple values. it works fine. it stored like this in my db table Afghanistan,Argentina,Austria,Bangladesh.
I have tried this code
<?php
$exp_str = explode(',', $model_availability);
foreach($exp_str as $get_str)
{
echo $get_str;
}
?>
This above code return this output AfghanistanArgentinaAustriaBangladesh
How do I put tick on the checkbox based on this value?
<?php
$sql = "SELECT * FROM ".TBL_COUNTRY." ORDER BY country_name ASC";
$exe = mysql_query($sql, $CN);
while($r = mysql_fetch_array($exe))
{
?>
<input type="checkbox" name="model_availability[]" value="<?=$r['country_name']?>" id="<?=$r['country_name']?>" />
<label for="<?=$r['country_name']?>"><?=$r['country_name']?></label>
<?php } ?>
<input type="checkbox" name="model_availability[]" value="<?=$r['country_name']?>" id="<?=$r['country_name']?>"<?=(in_array($r['country_name'],$model_availability)?" checked":"")?> />
//In the input box just add a checked attribute, you will get.
" id="" checked = "true" />

How to submit the multiple rows form data with a single submit in PHP

Here is my code.
I made a form with multiple rows which will be updated in a single submit.
I searched in forums, but didn't find the exact answer.
<form method='POST' action='demo24.php'>
<table width="500px" height="500px">
<tr><th>SETNAME</th><th>POST</th></tr>
<?php
$query = "SELECT name,setid FROM `set` LIMIT 0 ,10";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
while($row = mysql_fetch_array($result))
{
$output .='<tr><td><input type="text" value="'.$row['name'].' '.$row['setid'].'" name="name'.$row['setid'].'">'.$row['name'].'</td><td><input type="checkbox" value="'.$row['setid'].'" name="setid"></td></tr>';
}
echo $output;
?>
</td><td><input type='submit' value='submit' name='submit'/></td></tr>
</table>
</form>
Note that you can use something like name[] in multiple input fields to send an array to the server:
<input type="text" name="row[]" />
<input type="text" name="row[]" />
On the server side $_POST['row'] will look like this:
Array (
[0] => first_input,
[1] => second_input
)
You can do this for all fields (id, row, etc.) and then loop through $_POST['id'] etc. to get all entries back together. Be sure to validate enough, i.e. make sure that those fields are indeed arrays, that all are of the same size, etc.
The MySQL family of PHP is deprecated and support thereof will disappear. Please look into PDO or MySQLi to execute SQL code instead.
If your form method as 'post' then you can use this code :
if(isset($_POST['submit']))
{
$query = "SELECT name,setid FROM `set` LIMIT 0 ,10";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
while($row = mysql_fetch_array($result))
{
$id = $row['setid'];
$name = $_POST['name'.$id];
//here will be you update code. set value will be $name and update where setid = $id
}
}

Categories