I was wondering if you could tell me what is wrong with my code or point out where I am going wrong, as I am not able to display any results. $_POST['checkbox'] is an array.
<?
$get_id=$_POST['checkbox'];
if(empty($get_id)) {
echo("<h3>You didn't select anything.</h3>");
} else {
$where[] = sprintf(" id='%s'",$_POST["checkbox"]);
}
$where_str = " WHERE ".implode(" AND ",$where);
$sql = "SELECT * FROM products $where_str";
$result = mysql_query($sql, $link);
echo "<table>";
echo "<tr> <th>Description</th> </tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr><td>";
echo $row['description'];
echo "</td></tr>";
}
echo "</table>";
?>
You should refrain from using short tags <? as they are not supported after PHP 5.4.
You are not connecting to MySQL ($link undefined)
You are using a deprecated API (mysql_). See comments for alternatives (mysqli_ or PDO)
You should use the REQUEST_METHOD index of $_SERVER to determine whether your script has been posted.
if( $_SERVER[REQUESTED_METHOD] == 'POST' && !empty($_POST['checkbox']) ) {
... }
You need to use error handling to check for errors. If you echo $sql; you would see that the checkboxes aren't being populated:
SELECT * FROM products WHERE id=''
Your script is vulnerable to SQL injection. When you switch to current API, use binded parameters.
Is $_POST[checkbox] an array?
sprintf will not work as you intend it to because you are passing the entire $_POST[checkbox] array to it. You would need to iterate through it to format it. (See Ollie's answer)
Example
Assuming your HTML looks like this:
<form method="post" ...>
<input type="checkbox" name="checkbox[]" value="1" />
<input type="checkbox" name="checkbox[]" value="2" />
<input type="checkbox" name="checkbox[]" value="3" />
<input type="submit" name="submit" />
</form>
And all three boxes are checked; it will produce this array:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Following Collie's loop:
foreach ($_POST['checkbox'] as $checkbox) {
$where[] = sprintf(" id='%s'",$checkbox);
}
$where will look like:
Array
(
[0] => id='1'
[1] => id='2'
[2] => id='3'
)
The rest of your script should work. However, you should look into using the IN operator.
That will enable you to skip the loop and just use implode:
$where = "'" . implode("', '", $_POST[checkbox]) . "'";
Which produces:
'1', '2', '3'
And combined with IN:
$sql = "SELECT ... FROM WHERE id IN ($where)";
Be aware that this is not sanitized and you're still vulnerable to injection.
If $_POST["checkbox"] is an array like you say then you cannot use it as a string in the sprintf. Try using array_pop to return the last value of that array or similar.
You could foreach through each element in the array:
foreach ($_POST['checkbox'] as $checkbox) {
$where[] = sprintf(" id='%s'",$checkbox);
}
Although this will probably just create an invalid SQL statement if asking for ID to be equal to two different integers.
Related
So lately i have been working on a way to post values from a database through checkbox selecting. Thanks to a previous question: How to use checkboxes to retrieve specific data in a database, i managed to get it working!
Although i got it working, i wanted to make my queries a bit more effective when multiple checkboxes are selected instead of writing queries with if/else for every checkbox possibility.
Through some research on stack overflow, this topic in particular: Run a query based on multiple checkboxes, i created the code for my own project. Though, for some reason it just wont output the data correctly, it even wont output anything at all.
So i looked in my code to see where stuff goes wrong. I passed in several echo's to get array information etc, but it all seems ok EXCEPT the last echo where i am echoing the query results (which returns 0).
So i am kinda stuck now since i cant figure out what goes wrong.
NOTE: It is for wordpress so that explains the little difference in querying.*
The code is as follows:
The HTML Code to display the checkboxes
<form method="post">
<div id="list1" class="dropdown-check-list">
<span class="anchor">Select Authors</span>
<ul class="items">
<li><input type="checkbox" name="columns[]" value="Barry" />Barry</li>
<li><input type="checkbox" name="columns[]" value="Henk" />Henk</li>
<li><input type="checkbox" name="columns[]" value="Nicolas" />Nicolas</li>
</ul>
</div>
<input type="submit" name="go" value="Submit"/>
</form>
The ID is for a Jquery dropdown effect.
The PHP code is as follows:
*The code below defines the column titles that are being displayed/echo'd in a table
$column_names = array(
"Authorss" => "Authorss",
"Research_Source" => "Research_Source",
"Research_Title" => "Research_Title"
);
$sql_columns = array();
foreach($column_names as $i) {
$sql_columns[] = $column_names[$i];
}
The next lines of code checks the checked checkbox values and queries the selected values:
if(!empty($_POST['columns'])) { // empty() checks if the value is set before checking if it's empty.
foreach($_POST['columns'] as $key=>$value){
// Runs mysql_real_escape_string() on every value encountered.
$clean_criteria = array_map('mysql_real_escape_string', $_REQUEST['columns']);
// Convert the array into a string.
$criteria = implode("','", $clean_criteria);
}
$tmp = $wpdb->get_results("
SELECT"
.implode(",", $sql_columns)."
FROM
wp_participants_database
WHERE
authorss IN ($criteria)
ORDER BY
authorss ASC
");
}
If non is selected the query selects all possible results (this still has to be created tho since i want the specific select query to work first):
else {
echo 'still needs to be edit to show everything here';
//$tmp = $wpdb->get_results( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database;");
}
Now comes the part where the queried data is being showed/put in tables:
echo "<table>
<tr>";
foreach($column_names as $k => $v) {
echo "<th>$v</th>";
}
echo "</tr>";
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
}
echo '</table>';
*****UPDATE*****
Got it fixed myself! First i deleted:
$column_names = array(
"Authorss" => "Authorss",
"Research_Source" => "Research_Source",
"Research_Title" => "Research_Title"
);
$sql_columns = array();
foreach($column_names as $i) {
$sql_columns[] = $column_names[$i];
}
This above code was unnecessary as the columns were all preset, so i just echo'd them by typing them out.
The problem was the following:
$tmp = $wpdb->get_results("
SELECT"
.implode(",", $sql_columns)."
FROM
wp_participants_database
WHERE
authorss IN ($criteria)
ORDER BY
authorss ASC
");
The $criteria variable should give a string to the IN, though in my code it was parsed as an literal (so no string). It seemed very easy, i just had to add the '' so it would be parsed as a string. Result: WHERE authorss IN ('$criteria')
<div>
<?php
$corpServicesValue = $row['corp_services'];
$value= explode(",",$corpServicesValue);
if(in_array("1",$value))echo '<input type="checkbox" name="corporationServices[]" value="1" checked >Management<br>';
?>
</div>
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
}
}
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.
First of I apologize if this is a dumb question - I'm just starting to pick up my php/mysql skills. I'm making a dropdown form with 3 dropdowns. I want to be able to trigger a query from the form. You select Part Type, Make, Model hit submit and a table of results is displayed.
I have my form populated with 3 arrays and when you hit submit, I can echo the key of each selected item to the page:
echo '<form action="dbBrowse.php" method="post">';
$mak = array (0 => 'Make', 'Ford', 'Freightliner', 'Peterbilt', 'Sterling', 'Mack', 'International', 'Kenworth', 'Volvo');
$mod = array (0 => 'Model', 'Argosy', 'Midliner');
$p = array (0 => 'Part', 'Radiator', 'Charge Air Cooler', 'AC');
echo '<select name="drop1">';
foreach ($p as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '</select>';
echo '<select name="drop2">';
foreach ($mak as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '<select name="drop3">';
foreach ($mod as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '</form>';
//echo keys of selection
echo $_POST['drop1'];
echo "<br />";
echo $_POST['drop2'];
echo "<br />";
echo $_POST['drop3'];
//these echo something like 1, 1, 3 etc. to my page
Where I'm getting lost is I'm looking to take the selected options and insert them into a query something like this:
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" . AND WHERE make = "$makeTypeVar" . AND WHERE model = "$modelTypeVar"');
$partTypeVar being the corresponding value to the key that is being returned from the array.
I'm driving myself crazy trying to figure out how to make that happen. Eventually I want to expand this further but just being able to create a mysql statement with the values selected would make my day right now. I understand the concept of what needs to happen but I'm unsure of how to accomplish it. Any help or pushes in the right direction would be greatly appreciated.
First of all, you have to delete the . char in your SQL query, there's no need to use it for now and of course assign the correct values to the variables.
$partTypeVar = mysql_real_escape_string($_POST['$drop1']);
$makeTypeVar = mysql_real_escape_string($_POST['$drop2']);
$modelTypeVar = mysql_real_escape_string($_POST['$drop3']);
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" AND WHERE make = "$makeTypeVar" AND WHERE model = "$modelTypeVar"');
I am assuming that's the correct order of your variables.
I hope this help!
If I've understood your question, when the form is submitted, you want to query the database with the selected values.
Example using AND:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' AND make='%s' AND model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match those three values.
Example using OR:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' OR make='%s' OR model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match any of those three values.
You can read more about this:
mysql_query
mysql_real_escape_string
MySQL 5.6 Reference Manual :: 12 Functions and Operators :: 12.3 Operators
<select name="myFilter">
<option value="Chooseafilter" name="default">Choose a filter...</option>
<option value ="Lastname" name="opLastName">Last Name</option>
<option value="Firstname" name="opFirstName">First Name</option>
<select>
<li><!--TEXT SEARCH INPUT--><input type="text" name="search_filter" /></li>
...
dbconnection();#assume that all connection data is here
...
$filter = $_POST['myFilter']; #
...
switch($filter)
{
case "Lastname":
$selectedoption = "profile_name";
break;
case "Firstname":
$selectedoption="profile_first_name";
break;
case "Chooseafilter":
$selectedoption = "";
break;
}
$result = pg_query($db_con, "SELECT * FROM profile WHERE ".$selectedoption." LIKE'%$_POST[search_filter]%'");
$row = pg_fetch_assoc($result);
if (isset($_POST['submit']))
{
while($row = pg_fetch_assoc($result))
{
echo"<ul>
<form name='update' action='' method='POST'>
<li>Guest Last Name:</li>
<li><input type='text' name='profile_name_result' value='$row[profile_name]' /></li>
<li>Guest First Name:</li>
<li><input type='text' name='profile_first_name_result' value='$row[profile_first_name]' /></li>
<li><input type='submit' value='Update' name='update'></input></li>
...
i am new to php.I want to dynamically create check boxes upon the result fetched from MySQL.If i have 10 records in employee Table so it must create 10 check boxes with employee name as value.I had seen several tutorials to make array of check boxes etc but could not fix the problem.Please anyone there to help!!!
Try this out:
<?php
//Create the query
$sql = "SELECT `name` FROM Employees";
//Run the query
$query_resource = mysql_query($sql);
//Iterate over the results that you've gotten from the database (hopefully MySQL)
while( $employee = mysql_fetch_assoc($query_resource) ):
?>
<span><?php echo $employee['name']; ?></span>
<input type="checkbox" name="employees[]" value="<?php echo $employee['name']; ?> /><br />
<?php endwhile; ?>
The example you see above relies on two things to actually function properly:
You're using MySQL
Your SQL-query must retrieve the employees' names (so that you can use them in the loop
MySQL is just a source of data. The same process would apply to making a checkbox list from ANY data source (array, file contents, database, etc...). A skeleton framework for the process would be:
$sql = "select idfield, namefield FROM sometable ...";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo <<<EOL
<input type="checkbox" name="name[]" value="{$row['namefield']}" /> {$row['namefield']}<br />
EOL;
}
Note that I've use the "name field"as you specified. But consider the case where you've got 2 or more John Smith's working for you - it is far more reliable to use the employee's ID number (whatever it may be in your database) than their name.
Lets say the result you fetched is in the $result array.
The array has 10 sub-arrays - each one looking like this:
[0] => array
['name'] => 'ZainShah'
[1] => array
['name'] => 'Stack'
The easiest way to do this is:
foreach ( $result as $key => $employee ) {
echo '<label for="employee' . $key . '">' . $employee['name'] . '</label>'
echo '<input type="checkbox" name="employee[]" id="employee' . $key . '" value="' . $employee['name'] . '" />';
}
I have made it easy to create checkboxes as well as radio buttons in any php form. Only thing is I am using Codeigniter MVC framework.
Here is the function definition that you can insert in your common-model or any helper file.
function createOptions($fieldName, $labelsArray=array(), $selectedOption, $fieldType,$valuesArray = array()) {
$returnString = '';
if(count($valuesArray)!=count($labelsArray))
$valuesArray=$lebelsArray;
if ($fieldType === 'checkbox') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='   <input type="checkbox" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if(in_array($valuesArray[$i], $selectedOption)){
$returnString.=' checked="checked" ';
}
$returnString.=' />  <label>'.$labelsArray[$i].'</label>';
}
}
if ($fieldType === 'radio') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='  <input type="radio" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if($valuesArray[$i]== $selectedOption)
$returnString.=' checked="checked" ';
$returnString.=' /><label>'.$labelsArray[$i].'</label>';
}
}
return $returnString;
}
And, you have to call this function in view file as,
<?php
echo $this->common_model->createOptions('userHobbies[]', $hobbyOptions, $userHobbies, 'checkbox'); ?>
First parameter is name of checkbox field or radio field, which is always gonna be same for all options for both cases. Second is labels array, Third is selected options which will show those options as checked while loading the form. Fourth is type of field that will be a string as 'checkbox' or 'radio'. Fifth will be values array, which, if present, will contain values for labels in the same order as that of labels. If its absent, labels array will be teated as values array
This is fairly straightforward. I'll assume that your MySQL result data is in an array called $employees, containing at least 2 elements: id and name. You mention that the "value" of the checkbox needs to be the name, but I'll assume that's what you want displayed in the HTML next to the checkbox. It would be better to have the "value" be the id of the database record for each employee (since employees might have the same name). Creating the HTML for the checkboxes is simply a matter of iterating through them with a foreach() loop, and creating a php variable to hold the HTML.
So, assuming your $employees array looks something like this:
[0] =>
'id' => '1'
'name' => 'Sam Jones'
[1] =>
'id' => '2'
'name' => 'Tom Smith'
[2] =>
'id' => '3'
'name' => 'Sarah Conners'
Just need to run through the array and create the output:
// init the var to hold the HTML
$output = '';
// cook the HTML
foreach ($employees AS $k=>$v) {
$output .= "<input type='checkbox' name='employee_array[]' value='" . $v['id'] . "'> " . $v['name'] . "<br />";
}
In your HTML form, just echo the $output variable. Notice that the ".=" operand is used to append to the $output variable I created. And the "name" of the form field ends in "[]". This will create an array named "employee_array" that gets passed back to PHP when the form is submitted. Each item that is checked becomes an element of that array, with its value being the ID of the employee record.
Hope that makes sense...
set echo in for loop you will always be able to set the loop variablenow simply echo/print the code