I have a table with a list of users. Each one has assigned a checkbox. When the admin select some checkboxes my script saves some information into the database for the selected users.
Now, my issue is that beside that checkbox I want to have a text input type so the admin can leave a comment as well for that user. So, when the checkbox is selected and the input type has some data, the data gets saved as well.
This is what I've done so far (besides the obvious issues with security, that I haven't taken into account yet):
My list is generated by a loop for each user:
<input type=text name="infoAdicional" value="'.$x['infoAdicional'].'">
<input name="enviar['.$x['userID'].']" type="checkbox" value="'.$x['userEmail'].'">
I've taken the information and generated a foreach loop for the checkbox, but cannot get the additional information from the text field to get saved (it does update other values:
$userID = $_POST['enviar'];
$infoAdicional = $_POST['infoAdicional'];
foreach ($userID as $id => $email) {
$sql = "UPDATE cursosUsuarios
SET estadoCertificado = 'pending',
infoAdicional='$infoAdicional'
WHERE userID = '$id'
AND email = '$email'
";
...
}
I think that's because $infoAdicional = $_POST['infoAdicional']; should be inside the loop, but just inserting it inside it, gets every user with a selected checkbox to have the same additional information, it does repeat itself.
It doesn't matter if you put the variable $infoAdicional inside the loop or not. The thing is that the last input field with the name overwrites all and therefore you will only have the note of the last user for all. What you need to change is, to make usage of the [] name syntax as you did it with the checkbox.
So your name attribute of the notes field would look like this name="infoAdicional['.$x['userID'].']" and in the loop you would make the assignment of infoAdicional[USERID] to $infoAdicional.
So your code would look like this
$userID = $_POST['enviar'];
foreach ($userID as $id => $email) {
$infoAdicional = $_POST['infoAdicional'][$id];
$sql = "UPDATE cursosUsuarios
SET estadoCertificado = 'pending',
infoAdicional='$infoAdicional'
WHERE userID = '$id'
AND email = '$email'
";
...
}
And your HTML code
<input type=text name="infoAdicional['.$x['userID'].']" value="'.$x['infoAdicional'].'">
<input name="enviar['.$x['userID'].']" type="checkbox" value="'.$x['userEmail'].'">
Change your input parameters to:
<input type=text name="enviar['.$x['userID'].']['infoAdicional']" value="'.$x['infoAdicional'].'">
<input name="enviar['.$x['userID'].']['email']" type="checkbox" value="'.$x['userEmail'].'">
So your data will stick to specific user. Then your loop will be like this:
$userInfo = $_POST['enviar']; //Info here, right?
foreach ($userInfo as $userId => $info) {
$sql = "UPDATE cursosUsuarios
SET estadoCertificado = 'pending',
infoAdicional='$info['infoAdicional']'
WHERE userID = '$userId '
AND email = '$info['email']'
";
...
}
I've saved your syntax as it's your job to fill it with prepared statements etc.
Related
I have two input fields:
<input type='hidden' name='amenId[]' value='$amen[amenId]'>
<input type="checkbox" name='amentities[]' id='check'>$amen[amenBG]
These two input fields are in foreach tag which loops through an array($amen). After the form is submitted I have php file that loops through the array and insert the id of the checked input and the value. Now the problem comes from the fact that my input fields are checkboxes. I have used this technic for different array where the input type was text and I didn't have problems. Here I have around 30 choices to choose from and when I check the first one and the fifth one in the database where the ids of the choicse should be 1 and 5 but instead of that are 1 and 2. I'm not sure why is that but I'm thinking that it has to do with getting the values only from the checked boxes.
My php code:
$checkedAmen = '';
foreach ($_POST['amentities'] as $key => $amen) {
$checkedAmen = $amen;
$checkedId = $_POST['amenId'][$key];
if ($checkedAmen == "on") {
$checkedAmen = "Yes";
}elseif($checkedAmen == "") $checkedAmen ="No";
$sqlAmen = "INSERT INTO ObjectAmen(ProductId, AmenId, AmenData) VALUES(?, ?, ?)";
if ($stmtAmen = $db -> prepare($sqlAmen)) {
$stmtAmen -> bind_param('iis', $last, $checkedId, $checkedAmen);
}else{
echo "Error: " . $db->error;
}
$stmtAmen -> execute();
}
Can someone help me? I would like to have the correct ids correspoding to the checked choices in the database.
There's nothing currently tying both of your inputs together. You can have a value on a checkbox though, so if it's checked you have the id
<input type="checkbox" name='amentities[]' value='$amen[amenBG]'>
Also you want to take id's off the input if it's in a foreach, because you'll be rebinding the id every time.
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.
I have a little problem on database update activity.
Case study:
I created a form with PHP editing, and perform queries to retrieve the value of a record that wants to be updated. Excerpts of the script:
<?php
$row = mysql_fetch_assoc(mysql_query("SELECT id, field_1, field_2 FROM mytable WHERE id = $editid"));
?>
...
<form action="" method="post">
FIELD 1 <input type = "text" name = "f1v" value = "<? Php echo $ row ['field_1'];?>" />
FIELD 2 <input type = "text" name = "f2v" value = "<? Php echo $ row ['field_2'];?>" />
<input type="submit" />
</form>
....
// When the form posted
if ($_POST)
{
$f1v = $ _POST['f1v'];
$f2v = $ _POST['f2v'];
mysql_query("UPDATE mytable SET field_1 = '$f1v', field_2 = '$f2v' WHERE id = $editid") or die ();
// Redirect form
}
In this case I want when the form submited, there are activities to check whether there is a change in one or more fields values. Its logic approximately like this:
if ($ _POST)
{
// Compare
if the submitted value is different from the existing value in the record
{
Updated record
}
else
{
Do not update record
}
// Redirect form
}
Do you have any easy way to do it? Thank you for your help.
Don't bother checking. Just make sure the entry is valid and throw it in.
Keep two hidden fields with current values of the fields. After submitting the form check whether submitted values are different from the hidden field values.
I'm working on a homework assignment that involves PHP. Basically, I have a page that contains a web form that renders items pulled from a database. There's checkboxes on each row and 2 radio buttons. The user selects "accept" or "deny" and when submit is clicked, the items that are checked are supposed to change to that approval status. All of the items in the form are submitted into post. I thought that post is an array so I could just use a while loop with a counter so that the loop traverses through the array and when it gets to the last index (which should contain approve or deny). A query is generated that changes all of the previous indexes to approve or deny. I'm sorry if this isn't making much sense.
Here's a picture for more clarification
Here's the code I used to generate the webform:
<?php
#create a query string
$query = "SELECT * FROM Request WHERE superemail = '$user'";
#echo $query;
#run the query
$result = mysqli_query($link, $query) or die('error querying');
while($row = mysqli_fetch_array($result)){
#print out each row of the queryi
#line up the query results with temporary strings
$change = $row['KEY'];
$name = $row['first']. " " . $row['last'];
#echo $name;
$email = $row['email'];
#echo $email;
$type = $row['type'];
#echo $type;
$duration = $row['duration'];
$status = $row['status'];
#create a table row with the query results
echo "<tr><td><input type=checkbox name=$change /></td>
<td>$name</td>
<td>$email</td><td>$type</td>
<td>$duration</td><td>$status</td></tr>";
} #end while
?>
<label for=update>Change status to:</label><br />
<input type=radio name=update value=A />Approved<br />
<input type=radio name=update value=D />Denied<br />
<input type = submit value = "Change Status" />
Each input tag (your checkboxes and your radio button) in your html should have a name attribute, such as: <input type='radio' name='accept' value='1' />. When the form is submitted and processed by PHP, your script will be able to access that info at $_POST['accept'] (or $_GET['accept'] depending on the form's method).
So you should be able to specify a name for the radio button, then check to see if there is a value in the POST array at that index.
I am going to assume a few things. First, that it is a design goal of yours to only process items in your approval queue that you choose to select, leaving the others alone. Second, that you want to change their status to what is chosen in a radio button. Third, that you want both a code snippet and an explanation as to how the task got accomplished.
So, here goes.
You have a series of checkboxes; I assume they have the same name. If you wish for the values to be passed to PHP as an array, you absolutely need to name the inputs whatever[] with emphatic emphasis on the []! This is what creates an array from the checkbox to appear in the $_POST/$_GET. Only those items selected will appear in the array. The value ought to be something useful (A value in the corresponding database table, say) which you can select for and query on...after sanitizing the input, of course.
So, your HTML input tag should look like this:
<input type="checkbox" name="process[]" value="<?php echo $employeeName ?>" >
You should have this coming back at you...
$_POST['process'][array(0=>name1, 1=>name2/*...etc*/)]
...which you can loop through with a foreach at your leisure.
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.