HTML Form button in PHP While loop - php

I have a while loop in PHP that selects data from a database
I want to have a complete button for each row returned which, when pressed will run an SQL Query to change the value of the status column of that particular row
my while loop is:
$stmt = $pdo_conn->prepare("SELECT * from messages where status = :status and (assigned_to = :assigned_to1 OR assigned_to = :assigned_to2) ");
$stmt->execute(array(':status' => '', ':assigned_to1' => $user_result["sequence"], ':assigned_to2' => ''));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$i=0;
if(count($records) > 0) {
echo '<tr>
<td colspan="7">You have '.count($records).' Messages</td>
</tr>';
foreach($records as $Messages) {
$i++;
echo '<tr>
<td>'.AdminNameLookup($Messages["assigned_to"]).'</td>
<td>'.$Messages["caller_company"].'</td>
<td>'.$Messages["caller_telephone"].'</td>
<td>'.$Messages["caller_email"].'</td>
<td>'.$Messages["caller_message"].'</td>
<td><input type="submit" name="CompleteMessages['.$i.']" value="" /></td>
</tr>';
}
}
but I'm not too sure on how to handle the PHP on submit?

Before sending data you need to create html form tag. And also you have pass values using input tag values.
format tag should be like this below code.
<form action="" method="">
<input type="" value="">
<input type="submit" name="CompleteMessages['.$i.']" value="" />
</form>

I would use this instead:
<td><input type="submit" name="CompleteMessages" value="'.$i.'" /></td>
You can then get the id with:
$Id = $_POST['CompleteMessages'];
Personally I'd have $i set to $Messages["message_id"] to you can find what Id you have actually submitted.
You also need to wrap everything in a form tag:
<form action="submit.php" method="POST">
...
</form>

If you only want to change the value of the row where you clicked the submit button,
then you will need a unique key for each record.
Lets assume that the messages table has a MessageID column.
One approach would be to call a javascript function.
Let's say your javascript function was called UpdateColumn(ID,ColName,Index)
Here's what would need to be added to each input button (pseudocode)
onclick="UpdateColumn($Messages['MessageID'],'Status',$i)"
Then your javascript will need to lookup value from input CompleteMessages[Index]
The Javascript could call your request php via ajax ...
update.php?MessageID=MessageID&Column=Status&Value=CompleteMessages[Index].value
And finally your php which handles the submit would take the values
using
$MessageID=$_REQUEST["MessageID"];
$Column=$_REQUEST["Column"];
$Value=$_REQUEST["Value"];
Then you will want to run a sql query which updates your database accordingly.

Related

PHP struggling with POST array request

I have a table with a list of entries fetched by DB, each of them has a textbox, clicking a button, will do something with those textboxes. And until then, it's all good, however, when a user hits the Enter key on a textbox, the form is submitted but I can't figure out how to catch that POST request, because the 'name' value of the textbox is not fixed.
How would you do in such case?
FORM
<form action="file.php" method="POST">
<table>
<?php
while($row = $query->fetch_assoc()) {
?>
<tr>
<td><input type="text" value="<?php echo $_SESSION['arrays'][$idx]; ?>" name="array_<? echo $idx; ?>"></td>
</tr>
$idx ++;
}
</table>
<button type="submit" name="button">Submit</button>
</form>
WHERE I MANAGE THE POST REQUEST
if (isset($_POST['button']) {
//DO SOMETHING
}
If a user presses the enter key, the form is submitted but I have no idea how I can catch such request, what would be a good solution?
I tried replacing
if (isset($_POST['button']) {
with
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
but the problem persist, as I have no clue on how to get datas from the textbox, with the name not being fixed
EDIT SOLUTION
for those struggling with a dynamic field like this, I solved my issue adding an array hidden field to the table and fetching it with a POST.
<input type="hidden" name="idx[]" value="$idx">
then fetching the variable with
if (isset($_POST['idx'])) {
//this will work if user presses enter key on the dynamic textbox
}

PHP retrieving variables from a large SQL result set

I have been working on my own PHP project. I have hit an obstacle. I am trying to retrieve the results of a database and print out a form for each result set.
I then wish to interact with one particular result either be deleting it or passing it into a function etc..
Heres is my current code :
<?php
while($row = mysqli_fetch_array($result)){
echo '<div id="post">'; ?>
<form action="" method="post">
<?php
echo "<font size=4>".$row['post']."<br>";
echo "posted by : ".$row['username']."<br>";
$id = $row['p_id']; ?>
<input type="submit" name="choice" value="Y">
<input type="submit" name="choice" value="N">
</form>
<br>
</div>
}
<?php
if($_POST['choice']=="Y"){
// progress
functionA();
}
else if($_POST['choice']=="N"){
// delete or remove
functionB();
}
?>
So my goal here would be click Y to progress that particular result or N to delete/remove the result.
However currently by clicking either button all results either get deleted or progress. I do know that the id should be used to differentiate between posts but I cant quite seem to get it to work. Once the button is pressed it passes all results to either function.
First of all, I suppose you want to know the record to delete. So, add an input to your form:
<input type="hidden" name="id" value="<?php echo $row['p_id']; ?>">
Then, in your script, call:
if( $_POST['choice'] == "Y" )
{
// progress
functionA( $_POST['id'] );
}
elseif( $_POST['choice']=="N" )
{
// delete or remove
functionB( $_POST['id'] );
}
Additional problem: how you can use your db connection inside the functions? Assuming your mysqli connection is named $conn, call the function(s) in this way:
functionA( $_POST['id'], $conn );
Side note: First process $_POST values, then retrieve db records and print it.
Side note 2: take a look at prepared statement.
Read more about variable scope
Read more about prepared statements
Use two different <input type="radio">s for each item with the id in the value and let the user select which to delete and which to process.
So for an item with id 1 the outputted HTML would look like:
<input type="radio" name="items[1]" value="delete"><input type="radio" name="items[1]" value="process">
The name forces the items to go to _POST as an array with the ids as keys and the selected action as their values.
Example html: https://jsfiddle.net/gu1gkwod/

Inputting multiple values in database from HTML form using PHP

I'm trying to add multiple values into a database using PHP from an HTML. However, I can't just refer to the name attribute of the HTML form because each field in the form is generated by a PHP script. I've tried Googling around, but since I don't exactly know what I'm looking for, my search has been futile.
Here's the bit of code that I use to generate the HTML form:
<form action="input_points.php" method="post">
<?php
while($row = mysql_fetch_array($result)) {
echo $row['Name'] . ' <input type="text" name="userpoints">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
I don't know what names are currently in the directory so I need this piece of php to determine what names are in the database. Afterwards, I want to have a bunch of boxes for people to input points (hence the form). I'm having trouble figuring out how to link the particular text box with the user.
For example, if I have a text box for Bob, how would I link up the input text field that contains the number of points Bob earns with Bob's entry in the database?
I know you can do this with regular form fields:
$userpoints = $_POST['userpoints'];
UPDATE members SET points = $userpoints where $user = "Bob";
But since I have multiple users, how do I link up the correct database entry with the right user? Also, how would I determine which boxes are empty and which boxes are updated with a value?
If you want to update multiple filed then are using array
Please changes some code
<form action="input_points.php" method="post">
<?php
$userCount=mysql_num_rows($result);
echo '<input type="hidden" name="userCount" value="' .$userCount. '">';
while($row = mysql_fetch_array($result)) {
echo '<input type="hidden" name="userid[]" value="' .$row['id']. '">'; //Give the uniq id
echo $row['Name'] . ' <input type="text" name="userpoints[]">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
PHP Code -
$userCount = $_POST['userCount'];
for($i=1; $i=$userCount; $i++){
$userpoints = $_POST['userpoints'];
$userid = $_POST['userid'];
//UPDATE members SET points = $userpoints where $user = $userid;
//YOUR CODE HERE
}
The update you're trying to do is not safe unless you treat values to prevent SQL injection... but if you really want it, instead of mysql_fetch_array(), try using mysql_fetch_assoc().
Using mysql_fetch_assoc() you can extract the keys (database field names) with array_keys(). The keys will be your the name property of your form fields and the values of will be the fields' values.
Hope it helps.
You can use an array to store all the data that you need and add a hidden field that contains the missing data:
<form action="input_points.php" method="post">
<?php
for($i=0; $row = mysql_fetch_array($result); $i++ ) {
echo ' <input type="hidden" name="user[0]['name'] value ='". $row['name'] ."'">';
echo $row['Name'] . ' <input type="text" name="user[$i]['points'] ">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
Problem when you hit submit userpoints contain only the last value previous all values are overwritten
solution
name="userpoints"
must be different each time why not you define it in database and then fetch it just like you fetch $row['Name']?

Grabbing specific variable from while loop for form submit

I have a while loop generating information with a checkbox, I would like to update the database with the new "completed" value. How can I select the specific checkbox that is generated. Please help with showing me how I can grab the specific value of a checkbox and the task_name.
Thanks, Ryan
while ($row = mysql_fetch_array($query)){
$task_name = $row['task_name'] ;
$task_description = $row['task_description'];
$task_completed = $row['completed'];
$tasks .= '<div id="tasksBody">
<form action="" method="post">Completed? <input name="completed" type="checkbox" '.
($task_completed == 1?'checked="checked"':'').
' /><input type="submit" value="Update"><br /><br />
<b>'.$task_name.'</b><br /><br />'.$task_description.'<hr><br /></form></div>';
}
}
echo $tasks;
You need to name your input with something unique for the row, such as the task_name, or better, a database record ID.
Then when the user submits the form, you will use $_POST["YourTaskNameOrIDHere"] to check the value.
What you have currently calls all the check boxes the same thing.
EDIT: I'm sorry, you're isolating all of these in their own forms, I just realized that.
What you can add is an <input type="hidden" value="$task_name" name="TaskName" /> to the form, so you can look what the checkbox is corresponding to. Then, when the user submits the form, use $_POST["TaskName"] to find out the name of the task.
Add a hidden field to each of your forms containing the task_id
<form action="" method="post">
Completed?
<input name="completed" type="checkbox" <?=($task_completed == 1?'checked="checked"':'')?> value="1" />
...
<input name="task_id" value="<?=$task_id"?> type="hidden" />**strong text**
</form>
After submit:
if (isset($_POST['task_id']) { // form has been submitted
$task_id = $_POST['task_id'];
$completed = $_POST['completed'];
$sql = "UPDATE task SET task_completed=$completed WHERE task_id=$task_id LIMIT 1";
// code for updating database
// better use PDO or mysqli-* instead of old and deprecated mysql_*
}

Dynamically Setting Value With JQuery

I have a table of assignments. Within each row is a cell, that when clicked will bring up a hidden div to the right of the table. Within the div is a form that allows a user to associate a selected document with a task.
Currently the table is generated, in part, by a PHP "for" loop; I am cycling through an array and creating a new table row for each array index.
Within each row there are two table cells. I want the contents of one of the cells to be a hyperlink that, when clicked, will display a hidden div. Within the hidden div will be a form. The form will have a hidden input box, and I would like to dynamically set this value when the hyperlink is clicked.
Here is a sample of the table:
<table>
<tr>
<th>Task</th>
<th></th>
</tr>
<?php
for($i=0; $i<sizeof($task_array); $i++)
{ ?>
<tr>
<td><?php echo $task_array[$i]['task'];?></td>
<td>Attach Doc</td>
</tr>
}
?>
</table>
Here is the hidden div and form:
<div id="hidden_div">
<form action="[url]" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="hidden" id="task_id" value="">
<input type="submit" name="submit" value="Submit" />
</form>
</div>
I know that I can do the following with JQuery to display the hidden div:
$("#hiddendiv").show();
I also know that the hidden field 'task_id' can be set with JQuery by using
$("#task_id").val() = 'some value';
The problem I am having is that, since the values are coming from an array, I'm not sure how to specify a specific value. For example, the value of a task id is found in the variable $task_array[$i]['task_id']. I could try this:
$('#show_div').click(function(){
$("#hiddendiv").show();
$("#task_id").val() = ???
});
I'm sort of stuck on specifying for which iteration to use the task id value.
My apologies if that wasn't very clear. Any help would be appreciated. Thanks.
PHP
<?php
for($i=0; $i<sizeof($task_array); $i++)
{ ?>
<tr data-task-id="<?php echo $task_array[$i]['task_id'];?>">
<td><?php echo $task_array[$i]['task'];?></td>
<td>Attach Doc</td>
</tr>
}
?>
See that I added a data-attribute named data-task-id to the tr elements that stores the task_id for that row. We can use this in a click event handler later.
JS
//bind an event handler to the `tr` elements for the `click` event to show the `tr`s children elements (the `td`s)
$('tr').on('click', function () {
$(this).children().show();
//this next line is how we get the `task_id` associated with a row
$(this).attr('data-task-id');
});
//since we bound an event handler to the `tr` elements for the `click` event it's a good idea to stop the propagation of click events on links within the `tr` elements so the event doesn't bubble up the the `tr` elements
$('tr').find('a').on('click', function (event) {
event.stopPropagation();
});
Note that .on() is new in jQuery 1.7 and in this case is the same as .bind().
Also, you need to change the #show_div element's ID for each element (IDs must be unique). I recommend just changing it to a class instead of using an id:
<td>Attach Doc</td>
Then you can bind an event handler to it like this:
$('.show_div').click(function(){
$("#hiddendiv").show();
$("#task_id").val($(this).parents('tr').eq(0).attr('data-task-id'));
});

Categories