PHP struggling with POST array request - php

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
}

Related

Pressing 'update' button in my Php edit page while a field is empty removes the id from the URL

So I have a PHP CRUD system which adds, edits and deletes entries from/to a database. The CMS in question is a drugs table. I can add drugs to this table using the add button and filling in a form, I can also delete the drugs by simply deleting them. But the one of issue is the edit/update part of the system.
The edit feature itself works fine, I'm able to edit an entry and it will post to the database and show up in the table because the user gets redirected back to the table page which shows all the drugs, however, when I remove the text from a field, leaving it empty, and press update, I get an error message which says a text field is empty, however, I also notice the id at the top of the page is no longer there which gives me an Undefined index:error.
I've narrowed the problem down to it being simply because the input type "submit" removes it for some reason.
URL before pressing update with a text field empty:
php_files/DrugEdit.php?Drug_ID=23
URL after pressing update with a text field empty:
eMAR/php_files/DrugEdit.php
How the program works (with code):
Php variable created by getting the Drug_ID from the URL (in this case 23)
$Drug_ID = $_GET['Drug_ID'];
Then gets the field data from the database and assigns them to variables
$result = mysqli_query($conn, "SELECT * FROM drugs WHERE Drug_ID=$Drug_ID");
while($res = mysqli_fetch_array($result))
{
$Drug_Name = $res['Drug_Name'];
$Allergies = $res['Allergies'];
$Side_effects = $res['Side_effects'];
$Type_of_Medication = $res['Type_of_Medication'];
$Dosage = $res['Dosage'];
}
?>
The data is then shown in a form where I can edit the data
<form name="form1" method="post" action="DrugEdit.php">
<table border="0">
<tr>
<td>Drug_Name <?php echo $drug_name_error ?></td>
<td><input type="text" Name="Drug_Name" value="<?php echo $Drug_Name;?>"></td>
</tr>
<tr>
<td>Allergies</td>
<td><input type="text" Name="Allergies" value="<?php echo $Allergies;?>"></td>
</tr>
<tr>
<td>Side_effects</td>
<td><input type="text" Name="Side_effects" value="<?php echo $Side_effects;?>"></td>
</tr>
<tr>
<td>Type_of_Medication</td>
<td><input type="text" Name="Type_of_Medication" value="<?php echo $Type_of_Medication;?>"></td>
</tr>
<tr>
<td>Dosage</td>
<td><input type="text" Name="Dosage" value="<?php echo $Dosage;?>"></td>
</tr>
<tr>
<td><input type="hidden" Name="Drug_ID" value=<?php echo $_GET['Drug_ID'];?>></td>
<td><input type="submit" Name="update" value="Update"> </td>
</tr>
</table>
</form>
If the update button gets pressed, it runs the block of code below:
$drug_name_error = " ";
if(isset($_POST['update']))
{
$Drug_ID = $_POST['Drug_ID'];
$Drug_Name=$_POST['Drug_Name'];
$Allergies=$_POST['Allergies'];
$Side_effects=$_POST['Side_effects'];
$Type_of_Medication=$_POST['Type_of_Medication'];
$Dosage=$_POST['Dosage'];
// checking empty fields
if(empty($Drug_Name) || empty($Allergies) || empty($Side_effects) || empty($Type_of_Medication) || empty($Dosage)) {
if(empty($Drug_Name)) {
$drug_name_error = "<font color='red'>Drug_Name field is empty.</font><br/>";
}
if(empty($Allergies)) {
echo "<font color='red'>Allergies field is empty.</font><br/>";
}
if(empty($Side_effects)) {
echo "<font color='red'>Side_effects field is empty.</font><br/>";
}
if(empty($Type_of_Medication)) {
echo "<font color='red'>Type_of_Medication field is empty.</font><br/>";
}
if(empty($Dosage)) {
echo "<font color='red'>Dosage field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($conn, "UPDATE drugs SET Drug_Name='$Drug_Name' ,Allergies='$Allergies' ,Side_effects='$Side_effects' ,Type_of_Medication='$Type_of_Medication',Dosage='$Dosage' WHERE Drug_ID=$Drug_ID");
//redirecting to the display page. In our case, it is index.php
header("Location: ../drug_manager.php");
}
}
Thank you for taking the time to read my problem. Hopefully I've provided enough information for you.
input type "submit" removes it for some reason
Because you're submitting the form, and the URL for the form submit action is defined in the <form> element:
<form name="form1" method="post" action="DrugEdit.php">
Note that there's no Drug_ID value on that URL. However, in the form processing code you're not looking for it in the URL, you're looking for it in the form post:
$Drug_ID = $_POST['Drug_ID'];
So I'm not really sure where you're getting that error. But if somewhere in your form logic you're also looking for $_GET['Drug_ID'], or simply want it to be on the URL for some downstream need, then you can just add it to that URL:
<form name="form1" method="post" action="DrugEdit.php?Drug_ID=<?php echo $_GET['Drug_ID'];?>">

HTML Form button in PHP While loop

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.

onClick - selected (clicked) value in input box

i am retrieving data form database using a search query.
PHP code (which I'm using in search query to display search results)
echo "<span style='background-color= #FFFF00'>$query</span><br>";
$count=$dbo->prepare($query);
$count->execute();
$no=$count->rowCount();
if($no > 0 ){echo " <span>No of records = ".$no."</span>";
echo "<table><tr><th>PHONE NUMBER</th><th>OWNER NAME</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[ROLLNO]</td><td>$row[CNAME]</td></tr>";
}
echo "</table>";
i want to do like this,
when a user clicks on a phone number, it should redirect to a new page and in that new page, my input box should be filled with this phone number and should be submitted.
Input Box Code (which I'm using in page 2)
<form name="phone_number_form" id="phone_number_form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return vali()" >
<input type="text" name="number" id="number" />
<input type="submit" name="submit" value="Submit" />
</form>
Looking at w3schools PHP has a $_POST variable which is used to collect values from a form sent with method="post". There's also $_GET and $_REQUEST which seems to merge both post and get data. http://www.w3schools.com/php/php_post.asp
There are a couple of options like making a request (get) from your first page or post the data from your first page.
REQUEST Method
Heres how I think the request way to do it would work
PAGE 1
Amend the foreach that renders the table row to include an hyperlink to your second page
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[ROLLNO]</td><td>$row[CNAME]</td></tr>";
}
PAGE 2
Amend the textbox to be populated with the phone number from the request variable
<input type="text" name="number" id="number" value="<?php echo $_REQUEST["phoneno"]; ?>" />
POST Method
In your first page using javascript when the user clicks the phone number set a hidden field and submit the form to the second page. Again you should be able to read the hidden fields value from the $_REQUEST variable

How to escape other codes - php

i have a form with action='#'
that outputting some inputs
and a statement when the submit button clicks
if($_POST['edit'] == 'Edit')
{
manipulation here
with printout
}
what happen here is the output of the MAIN FORM
and the output of the IF STATEMENT print out when SUBMIT button is click
what i want is, when the SUBMIT button is click, ONLY the PRINTOUT on IF STATEMENT will shows.
Have you tried extending the if statement with an else - one or the other type of situation?
//when form is submitted
if($_POST['edit'] == 'Edit')
{
manipulation here
with printout
}
//when form not submitted
else
{
//display form
}
If I understand correctly, you do not want to display the form after it has been submitted. If that is the case, you can check to see if one of the values submitted by the form is set or not and display the original form based on that.
Here is an example:
<?php if( !isset($_POST['edit']) ): ?>
<form action="#">
<input type="text" name="edit" />
...
<input type="submit" value="Submit" />
</form>
<?php else: ?>
Display other information.
<?php endif; ?>

Two forms with multiple submit buttons in single PHP file

I am trying to write a dynamic form using PHP. I'd like to have a single webpage that contains two forms:
The upper form allows to search for an element in the mysql database, e.g., for a name
The lower form shows the data that is associated with this name in the database
If I press on the "Search" button of the upper form, then the the lower form is shown and the text fields are filled with data from the database that belong to this name. If I change the user name to some other value and press again "Search", then the data that is associated with the new record is shown and so on.
The lower form also has a button "Update" which allows to transfer changes made to the text boxes (in the lower part) to the database.
Now, I have the following problem: In my script I set initially the value of name (from the upper form) to "". When I then press the "Search" button, then the lower part of the form is shown and the corresponding data is shown in the lower part. When I then press the "Update" button, then the text field associated with name is set to the empty string. This is because in my script I set initially name to the "". I'd like that in this case the data entered in the upper form is not changed, i.e., it stays the same.
I guess, I am missing something here. There is probably an easy solution for this and I am doing something fundamentally wrong. It'd be great if you could help me.
That's what I tried... I deleted lots of details, but I guess that can give you an idea what I am trying to do. Notice that the whole code is in the file update.php.
<?php
function search_bus($mysql, $name)
{
// do some stuff here...
}
function update_bus($mysql, $b_id)
{
// do some stuff here...
}
// some global variables
$b_id = 0;
$username = ""; // username of business
// get b_id that corresponds to username
if (isset($_REQUEST['search']))
{
$b_id =0; // business id
if (isset($_POST['user']))
{
$username = $_POST['user'];
$b_id = search_bus($mysql, $username);
}
}
elseif(isset($_REQUEST['update']))
{
update_bus($mysql, $b_id);
}
?>
<h2>Search:</h2>
<form name="search_bus" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="submit" value="Suchen" name="search"/>
</form>
<?php
if($b_id != 0)
{
?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<-- some form follows here -->
<?php
}
?>
I think what you're missing is to create a HTML Hidden field to keep the value of Name variable.
<input type="hidden" name="name" value="<?php print $nameVar ?>" />
Add this input to both forms so you can keep the value no matter what button the user clicks.
Hope this helps.
Adding code to verify the
<h2>Search:</h2>
<form name="search_bus" method="post"
action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<input type="submit" value="Suchen" name="search"/>
</form>
<?php if($b_id != 0) { ?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];>">
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<-- some form follows here -->
<?php } ?>
Dont initialize $b_id if it already comes into the http request.
if (!isset($_POST['b_id']))
{
$b_id = 0;
}
else
{
$b_id = $_POST['b_id'];
}
This way you can alway remember the last selected value of b_id.
Hope this can help you.

Categories