I'm trying to put this,
check_box=147&check_box=148&check_box=146 etc..
into
$delete_selected = $connection->real_escape_string($_POST['check_box'])
$sql = "DELETE FROM categories WHERE cat_id = '$delete_selected'";
but it only deletes the first check_box value. Is there a way to loop through all the values?
You need to change your post vars to have [], i.e. checkbox[]=. Once that's fixed, on to the backend...
Considering you neeed to escape every value, do something like this:
$clean_values = array();
foreach($_POST['check_box'] as $value){
$clean_values[] = $connection->real_escape_string($value);
}
$sql = 'DELETE FROM categories WHERE cat_id in ('.implode(',',$clean_values).')';
BONUS PHP5.3 ANSWER:
array_walk($_POST['check_box'],function(&item) use($connection){
$item = $connection->real_escape_string($item);
});
$sql = 'DELETE FROM categories WHERE cat_id in ('.implode(',',$_POST['check_box']).')';
try
$sql = "DELETE FROM categories WHERE cat_id in '($delete_selected)'";
I may have screwed up the php. the resulting query should liik like
DELETE FROM categories WHERE cat_id in ('cat1', 'cat2', ...)
Self-contained example to play with...
<html>
<head><title>...</title></head>
<body>
<form method="post" action="?">
<p>
<!-- php will parse post fields like check_box[]=xyz as an array, appending new elements to $_POST['check_box'] -->
<input type="checkbox" name="check_box[]" id="c1" value="140" /><label for="c1">140</label><br />
<input type="checkbox" name="check_box[]" id="c2" value="141" /><label for="c2">141</label><br />
<input type="checkbox" name="check_box[]" id="c3" value="142" /><label for="c3">142</label><br />
<input type="checkbox" name="check_box[]" id="c4" value="143" /><label for="c4">143</label><br />
<input type="checkbox" name="check_box[]" id="c5" value="144" /><label for="c5">144</label><br />
<input type="submit" />
</p>
</form>
<?php
if ( isset($_POST['check_box']) && is_array($_POST['check_box']) ) {
echo '<pre> _POST='; var_dump($_POST); echo '<pre>';
// approach #1: treat ids as numbers. Keep the value range of php's integers and MySQL numeric fields in mind
// make sure the elements really are integers
$params = array_map('intval', $_POST['check_box']);
// join the elements to one string like "1,2,3"
$params = join(', ', $params);
// use the IN operator in your WHERE-clause
$sql = "DELETE FROM xyz WHERE cat_id IN ($params)";
echo 'sql1 = ', $sql, "<br />";
// mysql_query($sql, $mysql) or die(mysql_error());
// approach #2: treat ids as strings.
// you need a database connection for mysql_real_escape_string()
$mysql = mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test', $mysql) or die(mysql_error());
// each element has to be escaped and put into single quotes
$params = array_map(
function($e) use ($mysql) {
return "'".mysql_real_escape_string($e, $mysql)."'";
},
$_POST['check_box']
);
// again join them, "'1','2','x'"
$params = join(', ', $params);
// IN operator in WHERE-clause
$sql = "DELETE FROM xyz WHERE cat_id IN ($params)";
echo 'sql2 = ', $sql, "<br />";
// mysql_query($sql, $mysql) or die(mysql_error());
}
?>
</body>
</html>
Related
I'm wondering how I can delete selected (with checkbox) rows from a database that were printed using the foreach loop.
For now I only have this:
if(isset($_POST['submitS1'])) {
$myads = $wpdb->get_results( "SELECT * FROM ads ORDER BY id DESC");
foreach ($myads as $pointer2) {
$id_ad = $pointer2->id;
$title = $pointer2->title;
$text1 = $pointer2->text1;
$nme = $pointer2->name;
echo '<br><h2>Message:</h2>'.$text1.'';
echo '<br><h2>Title:</h2>'.$title.'<br>';
echo '<br><h2>Name:</h2>'.$name.'<br>';
echo ' <form method="post"><input type="checkbox" name="accept" value="accepto">Delete this ad<br>
</form>';
}
echo '<form method="post">
<input type="submit" name="submito" value="Delete selected ads">
</form>';
if(isset($_POST['submito'], $_POST['accept'])) {
$sql2 ="DELETE FROM `mydb`.`ads` WHERE `ads`.`id` = ".$id_ad."";
$wpdb->query($sql2);
}
}
Use only one form.
Set your checkbox names to be "delete_ids[$id]"
<input type="checkbox" name="delete_ids[<?php echo $id;?>]" />
PHP will process the POST data and give you a neat POST variable called delete_ids which contains an array of the ids you need to delete (as keys). Iterate over it... and delete.
$ids = array_keys( $_POST["delete_ids"] );
if(count( $ids ))
{
var_dump( $ids );
$ids = implode( ",", array_map( intval, $ids ));
$sql = "DELETE FROM... WHERE id IN ($ids)";
.....
Simple as that.
i have this form
<form method="post" action="process.php">
Name: <input type="text" name="name" value="">
<br />
English: <input type="text" name="english" value="">
<br />
French: <input type="text" name="french" value="">
<br />
<input type="submit" name="submit" value="Submit">
</form>
and we make this query on process.php
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."'
WHERE
`id` = '".$id."'";
and if i edit the table languages and add more languages the form dynamically will modify to lets say this example
<form method="post" action="process.php">
Name: <input type="text" name="name" value="">
<br />
English: <input type="text" name="english" value="">
<br />
French: <input type="text" name="french" value="">
<br />
Spanish: <input type="text" name="spanish" value="">
<br />
German: <input type="text" name="german" value="">
<br />
<input type="submit" name="submit" value="Submit">
</form>
and the query i need to dynamically be edited
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."',
`german` = '".utf8_encode($german)."'
WHERE
`id` = '".$id."'";
what i don't understand is how i make this dynamically inside the query the code
*the name of the form field is the same of the name of the variable i POST
*and the name of the column from the table is the same of the name of the POST
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."',
`german` = '".utf8_encode($german)."',
`other_language` = '".utf8_encode($other_language)."',
`other_language2` = '".utf8_encode($other_language2)."'
here above i have explained how i make the query but i cant understand how to write the variables
I know is a little bit difficult what i need but maybe someone understand what i need
thank you
Above this line is the edited message because someone flagged this message answered
I will explain first what i want to do:
I have a table called "translations" where i store the languages. ex: english, french, spanish, etc.
I use a form to update the new values, the problem is that i want to do it dynamically not to insert this query on every php file manually because the languages table will grow or edit and i want to work dynamically not to edit every php file.
the variable names are the same like fields name in database
i manage to make an array for the names on table translations
this is what i have until now to make it dynamic
the problem is i don't know how to insert variables in the query $_POST['english'], $_POST['french'], etc
$db = new DB();
$query = $db->query("SELECT * FROM `translations_languages` ORDER BY `name` ASC");
while($row = $query->fetch_assoc()){
$values[] = "`{$row['name']}` = '{$row['name']}'";
}
$dynamic_result = "".strtolower(implode(",", $values))."";
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
$dynamic_result
WHERE
`id` = '".$id."'
";
echo "$query";
and this is how the query looks normally
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."'
WHERE
`id` = '".$id."'";
i want to add these values to the query
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."'
you just need to create a dynamic update array. Something like this:
$languagesToUpdate = array();
// this is an example, you should modify as your script:
// create a variable/constant to make sure you update only allowed fields
$allowedLanguages = array('english' => true, 'french' => true, 'spanish' => true, 'german' => true, 'other_language' => true);
// iterate threw post and check for allowed languages and add to languagesToUpdate the language we need to update with it's value
foreach ($_POST as $post => $value) {
if (isset($allowedLanguages[$post]) && $allowedLanguages[$post]) {
$languagesToUpdate[] = '`' . $post . '` = "' . utf8_encode($value) . '"';
}
}
// add additional data like updated_on
$languagesToUpdate[] = '`updated_on` = ' . time() . '';
//update database
$db = 'UPDATE `translations_structure` SET '.implode(', ', $languagesToUpdate).' WHERE `id` = '.(int)$id;
// this will produce something like this:
// UPDATE `translations_structure` SET `english` = "English text", `spanish` = "Spanish text", `updated_on` = 1479720637 WHERE `id` = 1
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);
?>
I have a form that is dynamically created based off multiple mysql tables. This form sends to an external page for processing.
this means that my $_POST data will always be different. I need to extract the post array, strip it down and create a query.
here's the print_r of the Posted array:
Array ( [userid] => 1 [modid1] => on [fid1] => on [fid3] => on [fid5] => on [fid7] => on [fid8] => on [modid3] => on )
as you can see I have three parts to this userid, modid, and fid. the catch is, the only way I could pass the id's I need is to name the fields that. So each modid and fid are rows in the db. the number after that is the id that needs updating, and of course "on" is from the check box.
so end result would be something like:
to give a better idea here's how I would write the query normally
for modid1:
UPDATE table SET var = var WHERE modid = 1
for fid1
UPDATE table SET var = var WHERE fid = 1
heres the code that generated this array:
<form id="ajaxsubmit" method="post" action="modules/users/updaterights.php">
<?php
$modsql = mysql_query("SELECT * FROM modules")or die("Mod failed " .mysql_error());
while($row = mysql_fetch_array($modsql))
{
echo '<div class="rights">';
echo "<ul>";
$userid = safe($_POST['user']);
$id = $row['id'];
$sql = mysql_query("SELECT * FROM modpermissions WHERE userid = '$userid' AND modid = '$id'")or die("Mod died " .mysql_error());
$sql2 = mysql_fetch_array($sql);
$modper = $sql2['modpermission'];
if($modper == 1){
echo '<li><input type="checkbox" name="modid'.$row["id"].'" checked> <b>'.$row["name"].'</b></li>';
}
if($modper == 0){
echo '<li><input type="checkbox" name="modid'.$row["id"].'"> <b>'.$row["name"].'</b></li>';
}
if($row['features'] == 1)
{
echo "<ul>";
$sql = mysql_query("SELECT * FROM features WHERE modid = '$id'")or die("Features loop failed " .mysql_error());
while($row2 = mysql_fetch_array($sql))
{
$userid2 = safe($_POST['user']);
$id2 = $row2['id'];
$sql3 = mysql_query("SELECT * FROM fpermissions WHERE userid = '$userid2' AND fid = '$id2'")or die("features died " .mysql_error());
$sql4 = mysql_fetch_array($sql3);
$fper = $sql4['fpermission'];
if($fper == 1){
echo '<li><input type="checkbox" name="fid'.$row2["id"].'" checked> '.$row2['feature'].'</li>';
}
if($fper == 0){
echo '<li><input type="checkbox" name="fid'.$row2["id"].'"> '.$row2['feature'].'</li>';
}
}
echo "</ul>";
}
echo "</ul>";
echo '</div>';
}
?>
<p><input type="submit" id="submit" value="Submit" class="button"> <input type="reset" class="reset" value="Reset Form"> </p>
</form>
its a mess I know, im learning. If someone can understand my question and point me in the right direction to accomplish what Im attempting I would be grateful.
First thing to do is to store the old value as well as having the check box (using a hidden field).
I would also suggest as a minimum using a fixed character as a delimeter in your field names so you can explode the field name to easy get the part that is the id.
Also consider using joins rather than looping around one result, and for each one doing another query.
Your output script would look something like this:-
<form id="ajaxsubmit" method="post" action="modules/users/updaterights.php">
<?php
$userid = safe($_POST['user']);
$modsql = mysql_query("SELECT modules.id, modules.features, modules.name, modpermissions.modpermission
FROM modules
LEFT OUTER JOIN modpermissions
ON modules.id = modpermissions.modid
AND modpermissions.userid = '$userid'")or die("Mod failed " .mysql_error());
$PrevModuleId = 0;
while($row = mysql_fetch_array($modsql))
{
if ($PrevModuleId != $row['id'])
{
if ($PrevModuleId != 0)
{
echo "</ul>";
echo '</div>';
}
echo '<div class="rights">';
echo "<ul>";
$PrevModuleId = $row['id'];
}
echo '<li><input type="checkbox" name="modid_'.$row["id"].'" '.(($row['modpermission'] == 1) ? "checked='checked'" : "").'><input type="hidden" name="modid_old_'.$row["id"].'" value="'.$row['modpermission'].'"> <b>'.$row["name"].'</b></li>';
if($row['features'] == 1)
{
echo "<ul>";
$sql = mysql_query("SELECT features.id, features.feature, fpermissions.fpermission
FROM features
INNER JOIN fpermissions
ON features.id = fpermissions.fid
AND fpermissions.userid = $userid
WHERE modid = '$id'")or die("Features loop failed " .mysql_error());
while($row2 = mysql_fetch_array($sql))
{
echo '<li><input type="checkbox" name="fid_'.$row2["id"].'" '.(($row2['fpermission'] == 1) ? "checked='checked'" : "").'><input type="hidden" name="fid_old_'.$row2["id"].'" value="'.$row2['fpermission'].'"> '.$row2['feature'].'</li>';
}
echo "</ul>";
}
}
if ($PrevModuleId != 0)
{
echo "</ul>";
echo '</div>';
}
?>
<p><input type="submit" id="submit" value="Submit" class="button"> <input type="reset" class="reset" value="Reset Form"> </p>
</form>
You can then loop through each entry on the $_POST array, explode the key based on the _ character, check when the values have changed and if needs be do an update Or possibly you can use an INSERT instead, but using ON DUPLICATE KEY update type syntax (this way you can update many rows with different values easily).
Note you also need to put the userid value somewhere in your form (probably as another hidden field) so you have the value to process with the updates.
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";