Get a dynamic variable from POST - php

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).

Related

How to retrieve imploded array from a cell in an MySQL database through PHP

Thanks for taking the time to look at this question.
Currently, I have a piece of code that creates four checkboxes labeled as "Luxury, Brand, Retailer," and "B2B." I have looked into a number of PHP methods to create checkboxes, and I felt the implode() function was the most simple and suitable for my job. I have looked into a number of tutorials to create the implosions, however, they did not fit my criteria, as I would like the database values be reflected in the front-end. Currently in my database, the implode() works, therefore (for example), if I check "Luxury", "Brand", "Retailer", and press the "Submit" button, the three items "Luxury, Brand, Retailer" will be in that specified cell. It looks like my code works in the back-end, but these are my issues:
I am not exactly sure (despite multiple Googles) how to retrieve those values stored in the single-cell array, and have it selected as "selected" (this would "check" the box in the front-end)
Could someone kindly take a look at my code below and let me know what seems to be missing/wrong/erroneous so I could attempt the revisions? Anything would be appreciated, thank you!
<?
if (isset($_POST['formSubmit2'])){
$category = mysql_real_escape_string(implode(',',$_POST['category']));
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
$query = mysql_query("SELECT * FROM Spreadsheet LIMIT $firstRow,$rpp");
while($row = mysql_fetch_array($query)){
// Begin Checkboxes
$values = array('Luxury','Brand','Retailer','B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category[]" value="<?php echo $values[$i]; ?>" id="rbl_<? echo $i; ?>" <? if($row['category'] == $i) echo "checked=\"checked\""; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
<? } ?>
The best approach i can recommend given what you have is to, explode the values out of the db giving you a new array of all the select fields. Then use in_array to compare the list you have with this new list in the loop. then flag the checkboxs as needed.

Create update query for dynamic database

I am trying to update a row in a mysql database. To do this, I would use a simple query like this:
"UPDATE `contactinfo` SET `Company` = 'Google', WHERE `id` = '1';"
The problem is that the database is dynamic and users can add columns at any time. So I do not know the names of the columns. To find the names and create a form to post to the page that will actually do the mysql work uses this code:
<?php
$result = mysql_query("select * from contactinfo WHERE `id` = '".$rid."';");
if (!$result) {
die('Query failed: ' . mysql_error());
}
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result, $i);
if (!$meta) {
echo "ERROR";
}
$name = $meta->name;
$r = mysql_fetch_array(mysql_query("select * from contactinfo WHERE `id` = '".$rid."';"));
$content = $r[$name];
if($name != 'id') {
echo "<tr><td align='center'><div align='left'>Edit ".$name."</div></td></tr>";
echo "<tr><td align='center'><input type='text' value='" . $content . "' /></td></tr>";
}
$i++;
}
mysql_free_result($result);
?>
This creates a nice little table with input boxes that allow the user to edit the content of the row that has been selected. The row id number($rid) is used to identify which row needs to be changed.
My question is, how can I get the new content for the row from the posted form and create a query to update it? I can't seem to figure out how to dynamically get the names of the form as well as the new content to the write the query.
If any clarification is needed just let me know and all help is appreciated.
Thanks.
The easiest way is to name the fields in the form exactly how the name of the fields in the database are.
Lets say you have this form
<form action="">
<input name="field[firstname]">
<input name="field[lastname]">
<input name="field[address]">
</form>
You should probably be able to create the form based on the fields names too, you are probably already doing this.
In the file that processes the response you can do something like this:
foreach($_POST['field'] as $field_name => $field_value) {
$sql_str[] = "{$field_name} = '{$field_value}'";
}
This just goes through the 'field' array that comes from post and puts the proper update text into another array.
Then just do a
mysql_query("UPDATE contactinfo SET ".implode(',', $sql_str)." WHERE `id` = '".$rid."';")
To put it into the database.
What you can do is add a column in the database with a bit flag and if the user is new or old, the flag will reflect it.
that way you can update the user to say if it is new or old.
hope this helps.
You might do well to investigate whether there is an ORM framework that you could use.
Anyway, the simplest way to do what you want is to pass the name of the field in the INPUT field.
$content = AddSlashes($content); // You may need HTMLEntities() here
$field = <<<FIELD
<input type="text" value="$content" />
FIELD;
Also, another useful trick to employ is to either supply an array of "protected" fields, or specify a prefix that makes the field unchangeable. For example, you almost certainly do not want a user to be able to change the primary keys.
So you could generate the form with
if ('id' == $meta->name or 'pk' == $meta->name or (0 === strpos($meta->name, 'pk_')))
{
// This is a primary key field
$html .= <<<PKFIELD
<input type="hidden" name="{$meta->name}" value="{$contents}" />
PKFIELD;
continue;
}
if (0 === strpos($meta->name, 'hf_'))
{
// hidden field, ignored (can't be changed)
continue;
}
if (0 === strpos($meta->name, 'ro_'))
{
// read-only field, shown but without even the name
$html .= <<<ROFIELD
<input type="text" readonly="readonly" class="readonly" value="{$contents}" />
ROFIELD;
continue;
}
Or you could use a fixed-size prefix and an array of templates:
$fieldtpls = array(
'pk_' => '<input type="hidden" name="{NAME}" value="{VALUE}" />',
'ta_' => '<textarea name="{NAME}">{VALUE}</textarea>',
'ro_' => '<input type="text" value="{VALUE}" readonly="readonly" />',
);
then you analyze each field and apply a default unless a known prefix is used.
Your users would then have to name the fields accordingly. Another possibility is to allow for a "meta-table" to hold the type and handling of each table and field, but in that case you would need to complicate a bit the user interface by creating a sort of "admin editor" for the Meta table:
table field type rw parameters
users name text yes
users id hidden no
users role text no
users notes area yes class:"widearea"
...and that way be dragons ORM frameworks.

Dynamically creating checkboxes

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.='&nbsp&nbsp&nbsp<input type="checkbox" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if(in_array($valuesArray[$i], $selectedOption)){
$returnString.=' checked="checked" ';
}
$returnString.=' />&nbsp&nbsp<label>'.$labelsArray[$i].'</label>';
}
}
if ($fieldType === 'radio') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='&nbsp&nbsp<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

PHPMyadmin checkboxes displays "Array"

I've searched extensively but can't find an answer… Hope someone can help:
I'm a newbie PHP and MySQL user and have a problem with checkboxes.
I have a simple HTML page which contains checkboxes.
The page is linked up to a MySQL db in PHPmyadmin.
The HTML is:
<html><p>User1<input type="checkbox" name="Users[]" id="Users1" value="1"/></p>
<p>User2<input type="checkbox" name="Users[]" id="Users2" value="2"/></p>
<p>User3<input type="checkbox" name="Users[]" id="Users3" value="3"/></p>
<p>User4<input type="checkbox" name="Users[]" id="Users4" value="4"/></p></html>
What I want is for the person filling in the form to check 1 or more of the values and then for the checked values to be displayed in PHPmyadmin, so that I can export them.
However, when using this PHP:
$values = implode(',', $_POST['Users']);
All I get in PHPmyadmin is "Array", and I can't figure out how to get the actual values to be displayed.
Thanks in advance,
You can get all value checked by looping :
$userChecked = $_POST['Users'];
for ($i=0; $i<count($userChecked ); $i++) {
echo( ($i+1) . ") " . $userChecked [$i] . "<br/>");
}
This will display all id. Instead of echo the value you can insert them in your database or do what you want. The values will be loop inside : $userChecked [$i]
#Daok: Yes, that displays the values
on the results page, but in
PHPmyadmin, it still indicates
"Array". How do I get it to display
the values?
PhpMyAdmin is just a tool to administrate php/mysql. I guess you mean that you have "array" written in your database? If you do want all value inside a field (varchar) than you just have to implode:
$comma_separated = implode(",", $_POST['Users']);
//Code here to Insert to you database with ...value($comma_separated)...
If you want 1 row for each entry :
$userChecked = $_POST['Users'];
for ($i=0; $i<count($userChecked ); $i++) {
//Insert Sql statement here with value($userChecked [$i])
}
try
$values = implode(',', (array)$_POST['Users']);
or
Users=array();
$values = implode(',', $_POST['Users']);

How to check a check box if it's value is in DATABASE. PHP

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.

Categories