$_POST input not reaching handler page - php

i have a form it has a hidden input called id, when it submits it goes to a handler page and that filters other forms and decides what to do through a switch statement, this form is supposed to call a class function through the handler and send the id to the parameter of the function, but the id input is not reaching the handler, i checked by echo $id and nothing shows up so i'm sure the id is not sent to the function parameter, where is the error i can't find it i spent two hours looking for it.
the form
function showPassengerRides($db)
{
//fetching the data from database
$row=$stmt->fetchAll();
if($row)
{
foreach ($row as $stmt):?>
<form action="rideHandler.php" method="POST" class="rides" >
//echoing data from database
<input type = "hidden" name = "id" value = "<?=$stmt['id'] ?>" />
//i echoed here and it worked, so i'm sure the problem is not from the SQL statement
<button class="delete-button" name="formSubmit" value="delete">Delete</button>
</form>
<?php }
the handler page
switch ($_POST['formSubmit']) {
case 'delete':
$id = $_POST['id'];
//i echoed here but nothing showed up
$obj = new databaseUpdate();
$obj->deleteReservation($id, $db);
break;
}

Related

form action inside foreach works only for the first value of php

I have created a form where every time, it would store a different id during foreach loop
<?php
foreach ($res as $r) {
?>
<form id="clearitem" action="clearitem.php" method="POST" enctype="multipart/form-data">
<input type="text" name="clearitem" value="<?php echo $r['cart_id'];?>">
<button type="Submit">×</button>
</form>
<?php
}
?>
and the retrieval of the data works perfectly, it shows me each and every id one after another, but when I click the button (in this case to clear the item) it only works for the first value i.e. if I click the button for the second or the third value, it deletes the first one only, not the one corresponding to the button.
please do help, why this is happening and the appropriate solution, if anyone can provide!
the clearitem.php
if(isset($_POST['clearitem'])){
$clear=$_POST['clearitem'];
$sql = "DELETE FROM cart WHERE id=".$clear;
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully of id".$clear;
} else {
echo "Error deleting record: " . $conn->error;
}
}
So, I was able to solve this issue, and the solution is the "id" so when you are using foreach, for every iteration, it is re-creating the form with the different value of the input, of course!
But the problem is the id-field, even if the input value is different, but the id is same for every iteration and therefore, even if you click a different button i.e. the 2nd or 3rd, the POST request will consider the initial value as the actual value, i.e. the first iteration, just because the id was same!
It's similar to the concept of first-come-first-serve. Since the POST request getting the value of the first element correspondent to the id, therefore that will the final value of that specific id and no amount how many times you iterate, the value will not be updated if you use the same id.
The possible fix is to have a different id, with each different iteration and that was made possible with putting the foreach value in the id.
<?php
foreach ($res as $r) {
?>
<form id="clearitem<?php echo $r['cart_id'];?>" action="clearitem.php" method="POST" enctype="multipart/form-data">
<input type="text" name="clearitem" value="<?php echo $r['cart_id'];?>">
<button type="Submit">×</button>
</form>
<?php
}
?>
by this for every iteration, the value of the id will be different, like if cart_id are as:1, 2, 3 then the ids would be clearitem1, clearitem2, clearitem3. By this the POST request will be retrieving different values since the ids are different!
The system should be able to correctly process the submitted data according to the data value in each form in such a "multi-form" environment.
Hence the code below should work (tested):
<?php
$conn = new mysqli("localhost","dbuser","dbpassword","dbname");
$sql = "SELECT * FROM cart";
$stmt = $conn->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
foreach ($res as $r) {
?>
<form id="clearitem" action="clearitem.php" method="POST" enctype="multipart/form-data">
<input type="text" name="clearitem" value="<?php echo $r['cart_id'];?>">
<button type="Submit">×</button>
</form>
<?php } ?>
The following is the clearitem.php code
<?php
if (isset($_POST["clearitem"])) {
$conn = new mysqli("localhost","dbuser","dbpassword","dbname");
$sql = "delete FROM cart where cart_id=?" ;
$stmt = $conn->prepare($sql);
$id=$_POST["clearitem"];
$stmt->bind_param("i", $id);
$stmt->execute();
}
?>
<script>
alert("Done !");
if ('referrer' in document) {
window.location = document.referrer;
/* OR */
//location.replace(document.referrer);
} else {
window.history.back();
}
</script>

Get submit button value from multiple buttons php

I have a dynamic menu inside a form element code is here
<form method="GET" action="index.php">
<?php
display_menu(); // this function generates menu items
?>
</form>
after the menu is generated every menu item is a submit button of the above form I want to get input of a single element by name or id attribute of submit button, and load a post from database.
<form method="GET" action="index.php">
<input type="submit" name="page-1" id="page-1" value="page-1">
<input type="submit" name="page-2" id="page-2" value="page-2">
<input type="submit" name="page-3" id="page-3" value="page-3">
<input type="submit" name="page-4" id="page-4" value="page-4">
</form>
so when any input button is pressed the function display_post() is called. Code of the function is as follows:-
function display_post(){
$conn = mysqli_connect('localhost', 'root', '', 'posts') or die('cannot connect');
if($_SERVER['REQUEST_METHOD'] == 'GET' ){
$blog_post_id = $_GET["id"];
$sql = "SELECT * FROM blog_posts where id='blog_post_id' ";
$result = mysqli_query($conn, $sql) or die('cannot load');
while ($row = mysqli_fetch_assoc($result)){
if($row > 0){
echo '<div>'.$row['content'].'</div>';
}else echo 'no posts';
}
}
}
However, the display_post() method is called inside a content tag whereas the display_menu() is called inside another div.
So the problem is I'm unable to get the id of the to submit button any help will be appreciated thanks in advance.
When you click on the submit button you will get all inputs values of the form.
Do one thing put this statement print_r($_GET);exit; in display_post() as a first line and see what you get after clicking on submit button.
Note: 1. you want to get the value of clicked button then you should use javascript or jQuery and Ajax.
2. You can not get input fields value by fields ID.
ex. if we have field <input type="submit" name="page-1" id="page-1" value="page-1">
then we can get its value as:
echo $_GET['page-1'];
page-1 is the input field name.
You can make 5 different forms for each button and change the action to
action="index.php?id=1"
Then use $_GET['id']
Also change id='blog_post_id' " to id='$blog_post_id' "
If I am guessing right what is your difficulty then
$blog_post_id = $_GET['id'];
$sql = "SELECT * FROM blog_posts where id='".$blog_post_id."' ";//I modified this line
$result = mysqli_query($conn, $sql) or die('cannot load');

Run two completely different sqli queries inside one script

I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.

Using the result of a select clause for a where clause to MySQL

I have a MySQL database containing 12 columns. I created a dropdown from it using distinct values of the column named 'activity' and the column named 'logdate' which is a datetime.
Like this..
<form action="define_activity" id="activityform" method="post"> <!-- Form to select an activity -->
<select name="activities" id="select1"> <!-- List of activities -->
<option value="" selected="">Select One</option>
<option value="NewActivity" id="newactivity" onclick="newactivity();">New Activity</option>
<?php
foreach($db_found->query("SELECT DISTINCT activity, logdate FROM NetLog ORDER BY activity") as $act) {
echo ("<option value='$act[activity]'>$act[activity] of $act[logdate]</option>");
}
?>
</select>
<input type="submit" name = "Submit" />
</form>
This all works great. what I want to do is use the results of the selected option to do another query against the same database that pulls all of the records associated with the selected activity and logdate values. I know how to write the query but I don't know how to find and then use the selected values.
Can someone please show me how to get the selected value from the
Thanks in advance for your consideration.
I make some changes in your code, I didn't test it, but I think that's going to help you:
<?php
//Returns an associative array with the query result:
function select($yourSQLQuery){
//Array with result:
$result = array();
//Database conection
$db = new PDO($dsn,$username,$password);
$stmt = $db->query($yourSQLQuery);
//This going to save an array with your data:
$result = $stmt->fetchAll(PDO::FETCH_NUM);
$db = null;
return $result;
}
//*********************************************************************************************
//Do here your query:
$result = select("SELECT DISTINCT activity, logdate FROM NetLog ORDER BY activity");
//*********************************************************************************************
//Form handler:
if($_SERVER[REQUEST_METHOD] == "POST"){
//If the form was submited:
//Get selected activity
if ( isset($_POST['activities']) ) {
/*Instead of sending your activity you can send the number of the submitted record in $records, then extract activity and logdate and make your query:*/
$rowNumber = $_POST['activities'];
//Get your log date:
$act = $result[$rowNumber]; //if doesn't work try '$rowNumber'
$activity = $act['activity'];
$logdate = $act['logdate'];
//Pull records asocciated with submitted activity:
$sql = "SELECT * FROM putHereYourTable WHERE activity = '$activity' AND logdate='$logdate'";
$records = select($sql);
//Pulled activities are now in $records
//do something with the records that you want. e.g.:
print_r($records);
}
}
?>
<!-- Your HTML: -->
<form action="define_activity" id="activityform" method="post"> <!-- Form to select an activity -->
<select name="activities" id="select1"> <!-- List of activities -->
<option value="" selected="">Select One</option>
<option value="NewActivity" id="newactivity" onclick="newactivity();">New Activity</option>
<?php
foreach($result as $key => $act) {
//Send the number of register instead of $act[activity]:
echo ("<option value='$key'>$act[activity] of $act[logdate]</option>");
}
?>
</select>
<input type="submit" name = "Submit" />
</form>
You need to submit the form first.
<form action="define_activity" id="activityform" method="post">
You need to submit to a valid page in your action param. So if 'define_activity' is not a valid URL (ie: not handled by htaccess) then you need to either A) use the same script/file your using or B) create another page to handle the data.
I would do this:
<form action="process.php" id="activityform" method="post">
process.php
<?php
if ( isset($_POST['activities']) ) {
// do something with the submitted data
$selectedValue = $_POST['activities'];
}
Now you have the selected value. You have also any other value that is submitted in the form, $_POST['othervalue'].
For a clear view of what is sent, dump it.
die('<pre>' . print_r($_POST, true) . '</pre>');
or you could use var_dump: die( var_dump($_POST) );
Keith,
You have to remember that web applications work in a client server environment over the HTTP protocol.
After your page is done loading the first time, the php script is basically done executing. In order for more code to run, another request needs to be sent to the server. This happens when you either:
a) submit a form or click a link that sends a new http request to the page
b) make some javascript send a new HTTP request to the page.
Since you're just getting started, lets assume you just want that form to send the new request off to the page.
So at the top of your php script, just add this statement:
print_r($_REQUEST);
As you visit the page that is running the script both with and without clicking the submit post button, you will be able to see the various request parameters show up based on your form post. One of those params will be 'activity' .. just throw an if statement checking to see if that parameter is present, then run your query inside that if statement, using the value of 'activity'
if(isset($_REQUEST['activities'])) {
//do your query here..
}

PHP MySQL - How easy way to update the database when one or more fields value changed

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.

Categories