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
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>
I am trying to post some values from checkboxes to my database, at the moment it does post a value, but only the last selected value (I currently have 8 checkboxes). Below is what I am using the get the checkboxes:
<?
$data = mysql_query("SELECT * FROM members WHERE active='Yes' ORDER BY name") or die(mysql_error());
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo "<input type='checkbox' name='attendees[]'";
echo 'value="' . $result['name'] . '">';
echo " ";
echo $result['name'];
echo "<br>";
}
?>
So they successfully show in my form and I can tick as many as I want however when I check the database, only the last one is showing.
I have been reading around and it seems like I need to store them in an array however this is the bit I am finding hard to understand.
Could anyone help me so that all values selected are shown in the DB and not just the last one?
EDIT: Too long to fit into a comment so here is the code where it adds the values to the DB
<?php
if(isset($_POST['submit']))
{
$date = $_POST['date'];
$score = $_POST['score'];
$attendees = $_POST['attendees'];
$result = mysql_query("INSERT INTO quiz_results (date, score, attendees)
VALUES ('$date','$score','$attendees')",$connect);
echo "<div class='alert alert-info'><b>Event Added!</b> - You'll will now be taken back to the previous page.</div>";
echo "<meta http-equiv=Refresh content=4;url=add-result.php>";
}//end of if($submit).
?>
$attendees = $_POST['attendees'];
$attendees is an array. You can't simply store the PHP array in the database without first transforming it into a string. You could store it as a comma separated list:
if ( is_array($attendees) ) {
$attendees = implode(', ', $attendees);
}
But, what happens when an "attendee" has a name that contains a comma? You could serialize it:
if ( is_array($attendees) ) {
$attendees = serialize($attendees);
}
But, in either case, what happens when you want to filter your data based on attendee? Now you have more problems.
The best way to manage this data (Google: database one-to-many relationships) is to store the attendees in a separate table that looks something like:
quiz_id attendee_id
1 20
1 42
1 50
See my answer at how to select from database based on a match in category? for an example.
Looks like you need to give each checkbox a different name.
$i=0;
while($result = mysql_fetch_array( $data ))
{
echo "<input type='checkbox' name='attendees[$i]'";
$i++
...
and I hope $_POST['attendees'] is an array?
Then when you insert into quiz results, you will need to loop through the arrays and insert one row of elements at a time into the database, you cant just insert arrays directly like that and expect each element to automatically take their own row.
Hope it helps, let me know.
View
<?php
$data = mysql_query("SELECT * FROM members WHERE active='Yes' ORDER BY name");
$html = '';
//And we display the results
while($result = mysql_fetch_array( $data )) {
$html .= sprintf( '<input type="checkbox" name="attendees[]" value="%d"> %s' , $result['id'] , $result['name'] );
}
echo $html;
When you post the form...
<?php
$attendees = isset( $_REQUEST['attendees'] ) ? $_REQUEST['attendees'] : null;
if( !is_null($attendees) && is_array($attendees)){
foreach( $attendees as $attendee){
// do something.. with attendee id
}
echo 'Ids: '.implode(', ', $attendees);
}
I want to randomize a number of users selected by an administrator.
So first, I have a page that reads all the name from the "Users" table. Then I display the names with a checkbox next to it so the admin can deselect names that aren't going to participate.
<input name="User<? echo $rows['UserID']; ?>" type="checkbox" value="1" checked/>
So, it will set values like User1 = 1; User2 = 0; User3 = 1, and so on...
Next, I want to write to the database the users that were selected in the form so I can read that table again to randomize the participants. How do I read the dynamic variable from the previous form? I'm trying to read the variable from the POST and store it in the variable Player (i.e.: User1 value is stored in Player1 variable)... this but doesn't seem to work:
$x = 1;
while ($x <= $total_records) {
${"Player" . $x} = $_POST[ ${"User" . $x} ];
$x++;
echo "Player" . $x . " = " . ${"Player" . $x} . "<BR>";
}
The result is "Player1 = ", "Player2 = ". Always empty.
Any idea, or an easier way to do it? ;)
Thanks!
I would recommend a separate approach. Instead of creating a different name for each checkbox, how about making them an array and their values are the users' ids?
For instance:
<input type="checkbox" name="User[]" value="<? echo $rows['UserID']; ?>" />
Then, you'll only have to iterate over the submitted array:
if (isset($_POST['User']) && is_array($_POST['User'])) {
foreach ($_POST['User'] as $userId) {
// do something with the user id!
}
}
If you want to keep the list as, well, a "list" to be reused, you could implode() the array that's posted and explode() when you need to use it again:
$combinedIds = implode(',', $_POST['User']);
// now you have 1,3,17
$splitIds = explode(',', $combinedIds);
// now you have array(1, 3, 17)
You can store the list in the db, a session variable, etc. If you store in a session variable, you could also directly store the array (whichever's easier =P).
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 have inserted some check box values in mysql database using PHP
And in the below image i have fetch the values:
Now i need the o/p like the below image: The values which i inserted in the database should be checked
Hope now its clear.
Thanks in advance..
You should have a table of available options (in this case, something like a cities table), and then a user-to-cities look-up table. Then you can loop over the cities, but also fetch which cities the user has checked.
A sample, without knowing your database structure, would be as follows:
$uid = $_SESSION['user']['id']; // your logged in user's ID
$cities = array();
// get an array of cities
$sql = "SELECT id, name FROM cities";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$cities[$row->id] = $row->name;
}
// get an array of cities user has checked
$sql = "SELECT DISTINCT city_id FROM users_cities WHERE user_id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->city_id;
}
// this would be templated in a real world situation
foreach ($cities as $id => $name) {
$checked = "";
// check box if user has selected this city
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="city[]" value="'.$id.'" '.$checked.'/>';
}
If I understand you question properly, the obvious and simplest approach is that you need to fetch records from database and when producing HTML [in a loop ot something similar] check if that value exists in array to results. You haven't given us any examples of your DB structure or code, so you must figure it our yourself how to do it.
Usually, you insert the values into the database. After inserting, you should have access to the same values again. It's not clear how you set up your script, so let's assume you redirect to another script.
What you need to do is retrieve the values for the checkboxes from your database again. Then you know which are selected. This can be used to determine if your checkbox need to be checked or not.
Note:
I assume here that the result of your query is an array with
the selected Ids as a value.
I assume here that your fields are stored in the result of
some query and is basically an array
with Field Id as key and Field Name
as Value.
E.g., something like this:
<?php
// Retrieve values from database.
$resultArray = ... some code ... ;
?>
<?php foreach ($field_types as $field_name => $field_value): ?>
<input type="checkbox" name="<?php echo $field_name; ?>" value="<?php echo $field_value ?>" <?php if (in_array($field_name, $resultArray)) { echo 'checked'; }/>
<?php endforeach; ?>
This results in a checkbox which is checked, if the field_name is inside the result array (with your already checked results). Otherwise they're just rendered as unchecked checkboxes. Hope this is clear enough.