Update Database field on Form Submission - PHP - php

What This does is gets the data from the db where 'approve' field's value is '0'. Displays the form. Now what we want to do here is to UPDATE the value of the 'approve' field to '1' on the click of the "Approve" Button. I think there is some issue with the IF condition or something, not sure. No issue in connecting to the db. Or do i need to close the db connection or commit or something for update to take place, not sure. Thanks for the help.
require("dbconn.php");
// get the form data and store it in the database
// show database data
$query="SELECT * FROM page where approve=0";
$result=mysql_query($query);
if ($result)
{
print "<b>Approval pending for below listings.</b><br><br>";
while($row = mysql_fetch_array($result))
{
echo '<form name="submit_form" action="" method="post">';
$page_url = $row['page_url'];
$contact_number = $row['contact_number'];
$description = $row['description'];
$category = $row['category'];
$address = $row['address'];
$business_name = $row['business_name'];
echo "<input type=\"text\" name=\"business_link\" value=\"$page_url\" readonly><br/>";
echo "<input type=\"text\" name=\"contact_number\" value=\"$contact_number\" readonly><br/>";
echo "<input type=\"text\" name=\"description\" value=\"$description\" readonly><br/>";
echo "enter code here`<input type=\"text\" name=\"category\" value=\"$category\" readonly><br/>";
echo "<input type=\"text\" name=\"address\" value=\"$address\" readonly><br/>";
echo "<input type=\"text\" name=\"business_name\" value=\"$business_name\" readonly><br/>";
echo "<input type=\"Submit\" Value=\"Approve\" name=\"submit\"/>";
echo "</form>";
echo "<hr><br>";
if($_POST['submit_form'] == "submit")
{
mysql_query("UPDATE page SET approve='1' WHERE business_name='$business_name' AND contact_number='$contact_number' AND page_url='$page_url' AND description='$description' AND address='$address' AND category='$category'");
echo "Thank you!";
}
}
}
else
{
print mysql_error();
}

You are checking for "submit_form", but you should be checking for "submit" from your Submit button.

Change:-
if($_POST['submit_form'] == "submit")
to following:-
if(isset($_POST['submit']) && $_POST['submit'] == "Approve")
Also, you should put the above code after "require("dbconn.php");", like following:-
require("dbconn.php");
if(isset($_POST['submit']) && $_POST['submit'] == "Approve"){
// update query here
// show notification
// you can show form too
}else{
// display the form
}

Try to use the php code isset($_POST['submit']) and check whether button is submitting or not.Also remove the <input type="Submit"......> to <input type="submit"......>.Echo the SQL queries and check whether all values are coming in the query.

use
if(isset($_POST['submit_button_name']))

Related

update mysql datarow from php form with button

I am trying to update a php form that holds a few rows of mysql data. I have a button next to each row and when i click on that I want to update the row. The issue im having below is the ID is only set as the last row. How do i get this to push the ID to the button? So basically no matter what button i press i always get the same ID which is the last one to load.
if($result){
while($row = mysqli_fetch_array($result)){
$id = $row["ID"];
$beername = $row["BeerName"];
$beertype = $row["BeerType"];
$beerpercent = $row["BeerPercent"];
$beerdescription = $row["BeerDescription"];
$nowpouring = $row["NowPouring"] =='0' ? '' : 'checked=\"checked\"';
$glutenreduced = $row["GlutenReduced"] =='0' ? '' : 'checked=\"checked\"';
$beertogo = $row["BeerToGo"] =='0' ? '' : 'checked=\"checked\"';
echo "<form action='' method='POST'>";
echo "<tr><td><h6><input type=\"text\" size=\"5\" name=\"id\" value=\"$id\"></h6></td>";
echo "<td><h6><input type=\"text\" size=\"30\" name=\"BeerName\" value=\"$beername\"></h6></td>";
echo "<td><h6><input type=\"text\" size=\"30\" name=\"BeerType\" value=\"$beertype\"></h6></td>";
echo "<td><h6><textarea size=\"90\" style=\"width:250px;height:150px;\" name=\"BeerDescription\" value=\"\">$beerdescription</textarea></h6></td>";
echo "<td><h6><input type=\"text\" size=\"5\" name=\"Percent\" value=\"$beerpercent\"></h6></td>";
echo "<td><h6><input type=\"checkbox\" name=\"NowPouring\" value=\"true\" $nowpouring></h6></td>";
echo "<td><h6><input type=\"checkbox\" name=\"GlutenReduced\" value=\"true\" $glutenreduced></h6></td>";
echo "<td><h6><input type=\"checkbox\" name=\"BeerToGo\" value=\"true\" $beertogo></h6></td>";
#echo "<td><h6> <a href=\". $_SERVER["PHP_SELF"] .?id=".mysql_result($result,$j,'id')."\" onclick=\"\"></h6></td>";
echo "<td><h6> <button name=\"submit\" type=\"submit\" value=\"$id\">Save</button></h6></td>";
echo "</tr>";
echo "</form>";
}
}
if (isset($_POST['submit'])) {
$user = $_POST['submit'];
echo "<p style=\"color:#ffffff\">$id</p>";
#$delet_query = mysqli_query($mysqli, "UPDATE NowPouring SET NowPouring = '1' WHERE ID = '4'") or die(mysql_error());
if ($delet_query) {
echo '<p style="color:#ffffff">Beer with id '.$id.' is updated. To refresh your page, click ' . ' <a href=' . $_SERVER["PHP_SELF"] . ' > here </a></p>';
}
}
?>
The main problem I see here is that the while loop your code has is generating the same name for the inputs...
All of your "<button name=\"submit\" type=\"submit\" value=\"$id\">Save</button>" will have the same name, that's why it always has the last id as value.
Maybe you should try something such as..
<button name=\"$id_submit\" type=\"submit\" value=\"$id\">Save</button>
or if you want you can store it in an array..
<button name=\"submit[]\" type=\"submit\" value=\"$id\">Save</button>
You are seeing this result because the 'name' of each of your inputs is the same, so essentially you have a form with a bunch of elements that have the same names. You need to add a dynamic aspect to each name.
For example, you could update your output to something like this:
echo "<tr><td><h6><input type=\"text\" size=\"5\" name=\"id_$id\" value=\"$id\"></h6></td>";
Where each line adds the current id. Then when you retrieve the form data, you can append the submitted id to the field you want to update.
Have you considered using an AJAX approach so you can submit just the line in question and not have to reload the page and return the whole data set each time?
Make <form> for each submit button. Adding <form> in the while():
if($result){
while($row = mysqli_fetch_array($result)){
echo "<form action='' method='POST'>";
//...
echo "</form>";
}
}
Your form tag is placed at the wrong place.
It should be within:
while($row = mysqli_fetch_array($result)){
$id = $row["ID"];
//....
//....
echo "<form action='' method='POST'>";
echo"<tr>";
echo "<td>" . $id . "</td>";
//....
//....
echo "<td><button type='submit' name='submit'>Save</button></td>";
echo"</tr>";
echo "</form>";
}

Insert Validation foreach loop trouble

So, I have the following code: (Don't worry about SQL injections/mysql depreciation for now)
$required = array('uexam_id', 'usubject', 'uexam_date');
$error = false;
//VALIDATION: first check all required fields are not empty. if post has values
if(!empty($_POST))
foreach($required as $field)
if ( empty($_POST[$field]))
$error = true;
//a field was empty, show error
if ($error) {
die ("All fields required!!! <a href='examisud.php'> Back to PHP Form </a>");
}
//no error - try the query
elseif($error === false && !empty($_POST) )
{
$InsertQuery = "INSERT INTO Exam (exam_id, subject, exam_date) VALUES ('$_POST[uexam_id]','$_POST[usubject]','$_POST[uexam_date]')";
$result = mysql_query($InsertQuery, $con) or die('query Failure:'. mysql_error());
}
So when I navigate to this php form (examisud.php), I am first greeted by "All Fields required". I can then navigate back to the form and it works as normal inserting data and displaying errors if not all fields are filled in.
*How can I get the "All fields required" to not display on form page load and only when I need it to (when a field is left blank).
When I also update or delete fields I also get the "All fields required" error display. However everything updates/gets deleted as normal apart from the error popping up.
So basically I just need it to show up when a field is left blank in the insert query!
Thanks in advance for any help you can give me!
*Edit My form:
{
echo "<form action=examisud.php method=post>"; //HTML FORM ECHOED OUT BY PHP
echo "<tr>";
echo "<td>" . "<input type=text name=exam_id value=" . $record['exam_id'] . " </td>";
echo "<td>" . "<input type=text name=subject value=" . $record['subject'] . " </td>";
echo "<td>" . "<input type=text name=exam_date value=" . $record['exam_date'] . " </td>";
echo "<td>" . "<input type=hidden name=hidden value=" . $record['exam_id'] . " </td>";
echo "<td>" . "<input type=image name=update value=update id=submit src=images/update.png" . " </td>";
echo "<td>" . "<input type=image name=delete value=delete id=submit src=images/delete.png" . " </td>";
echo "</tr>";
echo "</form>";
}
echo "<form action=examisud.php method=post>";
echo "<tr>";
echo "<td><input type=text name=uexam_id></td>";
echo "<td><input type=text name=usubject></td>";
echo "<td><input type=text name=uexam_date></td>";
echo "<td>" . "<input type=image name=insert value=insert id=submit src=images/insert.png" . " </td>";
echo "</form>";
echo "</table>";
you have to check whether the form is submitted or not
for example if you have form submit like this
<input type="submit" name="submit">
then in your php check it like this
if(!empty($_POST['submit']))//means the form is submitted
{
//your code
}
else
{
//no form is submitted here display your form normally
?>
<form action="" method="POST">
......
......
<input type="submit" name="submit">
</form>
<?php
}
hope it helps you,all the best
This code should do it, explainations below.
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // check if the user submits data (POST) or just loads the page (GET)
$error = false;
$required = array('uexam_id', 'usubject', 'uexam_date');
foreach($required as $field) {
if (!isset($_POST[$field]) || empty($_POST[$field])) {
$error = true;
break;
}
}
if ($error) {
die("All fields required!!! <a href='examisud.php'> Back to PHP Form </a>");
} else {
$InsertQuery = "INSERT INTO Exam (exam_id, subject, exam_date) VALUES ('".mysql_real_escape_string($_POST["uexam_id"], $con)."','".mysql_real_escape_string($_POST["usubject"], $con)."','".mysql_real_escape_string($_POST["uexam_date"], $con)."')";
$result = mysql_query($InsertQuery, $con) or die('query Failure:'. mysql_error());
}
}
First off, you code has some serious security issues and should never not be used in production.
mysql_* functions are deprecated - use mysqli (which is very similar to mysql) or PDO_MYSQL.
Your code is vulnerable to SQL injection attacks, read this question on how to prevent them (either properly escaping values or using prepared statements).
Currently I used mysql_real_escape_string to escape the variables so this code should be safe.
Finally, my code should still fix your first issue since it checks if the user is actually submitting the form (by checking if the request method is POST) before running the validation, whereas your first code was running the validation (and failing) even if there was no data being submitted.

Multiple echoed delete-edit buttons in PHP event listener

I am trying a trivial PHP assignement. I am running my own SQL server locally and I have created a DB on it called student. This database contains many tables. One of them is called announcement. The fields of this table are id, date, subject, text.
I am asked to display those announcements to a user that has the authority to delete and/or modify those entries of the DB. Each entry needs to be seperated from the next one and each entry has to have it's own Delete and Edit button. New entries can also be added to the database so the # of entries currently on the DB is not known.
So far I have done something like this:
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("student",$db);
mysql_set_charset('utf8',$db);
$result = mysql_query("SELECT * FROM announcement",$db);
$announcementID = 1;
WHILE($myrow = mysql_fetch_array($result))
{
echo "<br><h2>Announcement No".$announcementID."</h2>";
echo "<input type=\"submit\" name=\"Delete\" value=\"Delete\"><input type=\"submit\" name=\"Edit\" value=\"Edit\"><br>";
echo "<br>Date: ".$myrow["date"];
echo "<br>Subject: ".$myrow["subject"];
echo "<br>Text: ".$myrow["text"];
$announcementID=$announcementID+1;
echo '<br><hr />';
}
?>
This is a part of a larger php file that displays a webpage with the entries properly formatted.
Although I do create the separate buttons needed for each distinct announcement I do not think this can work out since I can't create an ActionListener (forgive me but I do not know how this is called in PHP) for those buttons and I am not even sure it is possible considering that all of those buttons will have the same name. Any workaround?
For PHP to be able to indetify that the user has clicked the button, you would need to surround the each row of inputs.
I've improved your code a little, as we need to pass over the ID of the announcement to the delete-record.php script for it to be able to identify which record to delete from the table.
$db = mysql_connect("localhost", "root", "");
mysql_select_db("student",$db);
mysql_set_charset('utf8',$db);
$result = mysql_query("SELECT * FROM announcement",$db);
while($myrow = mysql_fetch_array($result))
{
echo '<form action="delete-record.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $myrow["id"] . '">';
echo "<br><h2>Announcement No".$announcementID."</h2>";
echo "<input type=\"submit\" name=\"delete\" value=\"delete\"><input type=\"submit\" name=\"edit\" value=\"edit\"><br>";
echo "<br>Date: ".$myrow["date"];
echo "<br>Subject: ".$myrow["subject"];
echo "<br>Text: ".$myrow["text"];
echo '<br><hr />';
echo "</form>";
}
And then in the delete-record.php you can go with this:
if(isset($_POST['id'], $_POST['delete'])) {
$announcementid = $_POST['id'];
mysql_query("DELETE FROM announcement WHERE id = $announcementid");
}
For future reference, instead of using $announcementID = $announcementID+1; you can simply use the post-incremental operator $announcementID++;
I also suggest you to read up on MySQLi or PDO's prepared statements to secure yourself against SQL Injections and other SQL vulnerabilities.
Make javascript redirection to delete script.
WHILE($myrow = mysql_fetch_array($result))
{
echo "<br><h2>Announcement No".$announcementID."</h2>";
echo "<input type=\"submit\" name=\"Delete\" value=\"Delete\" onClick=\"window.location='delete_announcement.php?announcemenID=".$announcementID."';\">"
echo "<input type=\"submit\" name=\"Edit\" value=\"Edit\" onClick=\"window.location='edit_announcement.php?announcemenID=".$announcementID."';\"><br>";
echo "<br>Date: ".$myrow["date"];
echo "<br>Subject: ".$myrow["subject"];
echo "<br>Text: ".$myrow["text"];
$announcementID=$announcementID+1;
echo '<br><hr />';
}
And delete_announcement.php connect to the DB and do
mysql_query("DELETE FROM announcement WHERE announcemenID=" . $_REQUEST["announcemenID"],$db);
Don't forget to make sure that $_REQUEST["announcemenID"] only hold integers.
For edit you will need to create separate page edit_announcement.php with all the fields editable.
Create a form around each row with a Delete button
WHILE($myrow = mysql_fetch_array($result))
{
echo "<form method='post' action='delete-record.php'>";
echo "<br><h2>Announcement No".$announcementID."</h2>";
echo "<input type=\"submit\" name=\"Delete\" value=\"Delete\"><input type=\"submit\" name=\"Edit\" value=\"Edit\"><br>";
echo "<br>Date: ".$myrow["date"];
echo "<br>Subject: ".$myrow["subject"];
echo "<br>Text: ".$myrow["text"];
echo "<input type='hidden' name='formID' value='$announcementID' />";
echo "<input type='submit' value='Delete row'/>";
echo "</form>";
echo '<br><hr>';
$announcementID=$announcementID+1;
}
Then in delete-record.php:
<?php
if(isset($_POST['formID'])){
// Delete record query here
}
...

php get value of submit button when value is a variable

I tried to search but was unable to find an answer for this question.
I am trying to get the value of the button in my submit button that is a variable.
CODE is as follows
$penrequest = "select * from request where status='pending';";
$penreg = mysql_query($penrequest);
echo "<form method='post' action=''>";
while ($row = mysql_fetch_array($peneg))
{
echo "<input type='submit' name='answer' value='$appdeny'>";
}
if (isset($_POST['answer']))
{
echo $appdeny;
}
Ok the code works...if you hit the button its caught by the if statement like its supposedt o be. the variable $appdeny is a messageID number filled from a mysql database which can change. When the user clicks a button i want to print the messageID of the number displayed as the value of the answer button.
Change:
echo "<input type='submit' name='answer' value='$appdeny'>";
to:
echo "<input type='submit' name='answer' value='" . $row['appdeny'] . "'>";
Change:
echo $appdeny;
to:
echo $_POST['answer'];
You also need to do:
echo "</form>";
after the while loop.

Check boxes checked?

Now I've done a lot of research, tried a lot of methods in PHP, including $_POST isset..
foreach
etc
But i need some help!
Basically, just want to check if the checkboxes have been checked. And THEN, add 1 to the number of $visits made if the checkbox has been checked.
As long as I can check if the checkbox is checked, i think i can figure it out from there!
Thanks in advance
( note: $visits is the number of times a property has been visited. This coding displays property information read from a file)
<?
$filename = "house.txt";
$filepointer = fopen($filename,"r"); // open for read
?>
<html>
<head>
<h1> Search for properties</h1>
<form method = "post" action= "visit.php">
Enter max price
<input type = "text" name = "max" value="<?=$Max;?>">
<input type = "submit" name = "submit">
<br><i><p>Properties found</p></i></br>
</form>
</head>
</html>
<?
$myarray = file ($filename);
for ($mycount = 0; $mycount < count($myarray); $mycount++ ) { // one input line at a time
$aline = $myarray[$mycount];
$postcode = getvalue($aline,0);
$value = getvalue($aline,1);
$image = getvalue ($aline,2);
$visits = getvalue($aline,3);
$Max = $_POST['max'];
if ($value < $Max) {
print "<table border = 2>";
print "<FORM METHOD='POST' ACTION='visit.php' >";
print "<td> <input type='checkbox' name='check' value='Yes' > $postcode </td><BR> \n";
print "<td>$value <BR>";
print "<td>$image<BR>";
print "<td>$visits<BR><p>";
print "</table>";
print "</form>";
}
}
function getvalue ($aline, $commaToLookFor) {
$intoarray = explode(",",$aline);
return $intoarray[ $commaToLookFor];
}
if (isset($_POST['check']) && $_POST['check'] == 'Yes') {
echo "checked!";
} else {
echo "not checked!.";
}
?>
You're submitting a different form than the one you think you are...you have two forms on the page, both submitting to "visit.php". This line shouldn't exist:
print "<FORM METHOD='POST' ACTION='visit.php' >";
...since you've already created the form at the top of your file.
This will require a little reorganization of your code, but the basic idea is that you want one and only one form that contains all the fields and the submit button, otherwise you're submitting the form that contains the max price and nothing else.
Alternatively, if you actually do need separate forms (I'm not familiar enough with your use case to be sure), then the second form would need its own submit button.
Simplified working code:
print "<table border = 2>";
print "<FORM METHOD='POST' ACTION='visit.php' >";
print "<td> <input type='checkbox' name='check' value='Yes' > $postcode </td><BR> \n";
print "<td> <button type='submit'>Submit</button> </td><BR> \n";
print "</table>";
print "</form>";
//personally I would just check for isset($_POST['check']), but it doesn't really matter...
if (isset($_POST['check']) && $_POST['check'] == 'Yes')
{
echo "checked!";
}
else
{
echo "not checked!.";
}

Categories