PHP MySQL Statements not Updating Database - php

After much editing and checking tutorial sites. Code currently not calling info from Database and when clicking Approve button, does not edit database. I do have a column identifier named Reg_ID which can specify which column of data you choose to edit. The form is submitting, just clears the information that I enter in and doesn't store the data.
This file is named Approve Deny Prayer Request.
<?php
$DB_HOST = "XXXXXXX";
$DB_NAME = "XXXXXXX";
$DB_PASS = "XXXXXXX";
$DB_USER = "XXXXXXX";
$link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($link->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
$query = "SELECT * FROM Request";
$result = mysqli_query($link,$query); //<----- Added link
$row = mysqli_fetch_array($result);
if(isset($_POST['add'])){
$id = mysqli_real_escape_string($link,$_POST['id']);
$firstname = mysqli_real_escape_string($link,$_POST['first']);
$lastname = mysqli_real_escape_string($link,$_POST['last']);
$phone = mysqli_real_escape_string($link,$_POST['phone']);
$query2=mysqli_query($link,"UPDATE Request SET Reg_F_Name='$firstname', Reg_L_Name='$lastname',Reg_Request='$phone' WHERE id='$id'" );
if($query2){
header("Location: fbcaltusprayerorg.ipagemysql.com");
}
} // brace if(isset($_POST['add']))
?>
<form action="" method="post">
<table>
<input type="hidden" name="id" value="<? echo "$row[Reg_ID]" ?>">
<tr>
<td>First Name:</td>
<td><input type="text" name="first" value="<? echo "$row[Reg_F_Name]" ?>"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="last" value="<? echo "$row[Reg_L_Name]" ?>"></td>
</tr>
<tr>
<td>Prayer Request:</td>
<td><input type="text" name="phone" value="<? echo "$row[Reg_Request]" ?>"></td>
</tr>
</table>
<input name="add" type="submit" id="add" value="Approve Prayer Request">
</form>

Firstly, your initial code did not contain an opening <form> tag; that has been included below.
The way you're attempting to run your code is leaving you open to SQL injection.
Use prepared statements, or PDO
Now, here's what you need to do.
Create a column named id and set it to AUTO_INCREMENT if needed, but not required; just as long as there is some data related to it and holds a unique name/id.
Create a hidden field called/named id
Then use UPDATE along with SET and a WHERE clause.
Sidenote: This will automatically redirect you to the page's filename you've called it.
In this example, I used header("Location: http://www.example.com/update.php");
Replace the DB credentials with your own.
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($link->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
$query = "SELECT * FROM Request";
$result = mysqli_query($link,$query); //<----- Added link
$row = mysqli_fetch_array($result);
if(isset($_POST['add'])){
$id = mysqli_real_escape_string($link,$_POST['id']);
$firstname = mysqli_real_escape_string($link,$_POST['first']);
$lastname = mysqli_real_escape_string($link,$_POST['last']);
$phone = mysqli_real_escape_string($link,$_POST['phone']);
$query2=mysqli_query($link,"UPDATE Request SET Reg_F_Name='$firstname', Reg_L_Name='$lastname',Reg_Request='$phone' WHERE id='$id'" );
if($query2){
header("Location: http://www.example.com/update.php");
}
} // brace if(isset($_POST['add']))
?>
<form action="" method="post">
<table>
<input type="hidden" name="id" value="<? echo "$row[id]" ?>">
<tr>
<td>First Name:</td>
<td><input type="text" name="first" value="<? echo "$row[Reg_F_Name]" ?>"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="last" value="<? echo "$row[Reg_L_Name]" ?>"></td>
</tr>
<tr>
<td>Prayer Request</td>
<td><input type="text" name="phone" value="<? echo "$row[Reg_Request]" ?>"></td>
</tr>
</table>
<input name="add" type="submit" id="add" value="Approve Prayer Request">
</form>

where is the call to update the database with your sql statement?
I have a function that normally I just for update of the database. I also make sure to add column for each table like UpdateDtTm and add that to the end of my update. That way you know you are going to always update something on an update statement. Also make sure to use a key and a unique id to make sure you only update the row you want.
Also, try using this syntax
$query2 = "Update Request set Reg_F_Name = $row[Reg_F_Name], Reg_L_Name = $row['Reg_L_Name], Reg_Request = $row['Reg_Request'], UpdateDtTM = Now() where <A UNIQUE KEY ROW> = <UNIQUE ID>.
$result = db_update ("updating request in some location", $sql,"update");
function db_update($function_name,$sql,$type) {
// Get access to PHP global variables
global $database;
//if the database value is not pulled from the global array make sure
//the system has it based on the Session value set on load
if (! $database) {
$database = $_SESSION['database'];
}
// Now authenticate the user with the database
$db = db_connect($database);
// Run SQL Query
mysql_query($sql);
// Mysql won't return a $result for UPDATE, so have to test with mysql_affected_rows
// mysql also won't do an update if the values are the same, so you could
// possibly have an instance where nothing is change and this fails
// got around this by adding an updated column that is increased by 1 everytime
// an update is performed. this ensures that you always have something updated
if ( mysql_affected_rows()==0 ) {
// Unable to update
$error = "db_update error<br>$sql<br>".mysql_errno()." - ".mysql_error();
database_error($error,$sql);
// Exit the function after error
exit;
}
// Do nothing for this guy
// We don't need to return anything
return;
}

Related

Display and update MYSQL data via HTML form via PHP

I am trying to figure out how to display all the rows of a database table in one page, all the values to be editable, and for there to be a single submit button at the end of it. I got half the equation figured out, but for some reason it is still not working.
What I currently have is a table displaying all the contents of a MYSQL table and all fields are editable. There is a submit button for all each field (which is not what I want, but willing to settle if I have to), but upon editing something from the database fields, it brings me to a page that gives me a syntax error:
"Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE idnum = '0000'' at line 1"
The following is from FORM.PHP
<?php
include('config.php');
$result = mysqli_query($connect,"SELECT * FROM table123");
?>
<html>
<table>
<?php while ($res = mysqli_fetch_array($result)) { ?>
<tr>
<form action="test.php" method="post">
<td><input type="text" name="ret" value="<?php echo $res['ret']; ?>"></td>
<td><input type="text" name="code" value="<?php echo $res['code']; ?>"></td>
<td><input type="text" name="status" value="<?php echo $res['status']; ?>"></td>
<td><input type="hidden" name="idnum" value="<?php echo $res['idnum']; ?>"></td>
<td><input type="submit" name="update" value="Submit"></td>
</form>
</tr>
<?php } ?>
</table>
</html>
The following is from TEST.PHP
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$connect = mysqli_connect($servername, $username, $password, $dbname);
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['update'])) {
$sql = "UPDATE ssoretailerlist SET ret = '$_POST[ret]', code = '$_POST[code]', status = '$_POST[status]', WHERE idnum = '$_POST[idnum]'";
} else {
echo "Nothing was posted";
}
if (mysqli_query($connect, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connect);
}
mysqli_close($connect);
Syntax error is because you have an extra comma. Remove the comma before WHERE and you should be fine.
$sql = "UPDATE ssoretailerlist
SET ret = '$_POST[ret]', code = '$_POST[code]', status = '$_POST[status]'
WHERE idnum = '$_POST[idnum]'";
There is a submit button for all each field. Instead of creating a new form and submit for every row inside the loop, one them each once manually outside the loop.
<?php
include('config.php');
$result = mysqli_query($connect, "SELECT * FROM table123");
?>
<html>
<table>
<form action="test.php" method="post">
<?php while ($res = mysqli_fetch_array($result)) { ?>
<tr>
<td><input type="text" name="ret" value="<?php echo $res['ret']; ?>"/></td>
<td><input type="text" name="code" value="<?php echo $res['code']; ?>"/></td>
<td><input type="text" name="status" value="<?php echo $res['status']; ?>"/></td>
<td><input type="hidden" name="idnum" value="<?php echo $res['idnum']; ?>"/></td>
</tr>
<?php } ?>
</table>
<input type="submit" name="update" value="Submit"/>
</form>
</html>
You may want to also handle the output you're inserting into the form. If the data has double quotes in it, it may break your HTML. Check out htmlspecialchars(). Based on your column titles I don't think it would, but always good to keep in mind.
However, every single row has the exact same input names. This is a problem. How will it know which ret, code, status, or idnum to choose and associate together? First you want to turn the names into arrays. Then you want to loop through the idnum array and do multiple UPDATE queries accessing the same key location in the other arrays. Post a new question if you get stuck working on that.
And finally your config.php file is pretty necessary. You may want to read this thread about require_once() vs include(). It's good to throw an error and handle it if the include fails instead of continuing to process the rest of the script.

PHP form can't be updated

I am currently making a system for a client database management. There are four tables in mySQL for this system, which are; admin, staff, client, and project. The project table has one foreign key from the client table, which is the clientid.
Now, I have made forms for all these tables so that the user can input the data into them. Weirdly, the only form that can be updated successfully is the staff one. Both the client and project forms cannot be updated at all. It returns as successful, but the data are not altered.
Below is the staff update code.
<?php
include 'database.php';
$staffid = $_GET['staffid'];
$sql = "SELECT * FROM staff WHERE staffid='$staffid'";
$result = mysqli_query($conn,$sql);
while ($row=mysqli_fetch_array($result)){
$staffname = $row['staffname'];
$staffemail = $row['staffemail'];
$staffphone = $row['staffphone'];
}
if(isset($_POST['submit'])){
$staffname = $_POST['staffname'];
$staffemail = $_POST['staffemail'];
$staffphone = $_POST['staffphone'];
$sql = "UPDATE staff SET
staffname='$staffname',staffemail='$staffemail',staffphone='$staffphone' WHERE staffid='$staffid'";
$result = mysqli_query($conn,$sql);
if($result){
echo "<table><td><tr><h4>Record has been updated successfully!<br></tr></td></h4></table>";
}
else {
echo "<h4>Record has <b>NOT</b> been updated successfully<br></h4>";
}
}
?>
<form action="" method="post">
<table class ="table1">
<tr>
<td>Staff Name:</td> <td><input type="text" name="staffname" size="50" value="<?php echo $staffname;?>"></td>
</tr>
<tr>
<td>Staff Email:</td> <td><input type="text" name="staffemail" size="50" value="<?php echo $staffemail;?>"></td>
</tr>
<tr>
<td>Staff Phone No:</td> <td><input type="text" name="staffphone" size="50" value="<?php echo $staffphone;?>"></td>
</tr>
<td><input type="submit" value="Update" name="submit"> <input type="button" value="View" name="view" onclick='location.href="viewstaff.php"'></td>
</table>
</form>
Okay now is the update code for the client table.
<?php
include 'database.php';
$clientid = $_GET['clientid'];
$sql = "SELECT * FROM client WHERE clientid='$clientid'";
$result = mysqli_query($conn,$sql) or die ("Error in query: $query. ".mysqli_error());
while ($row=mysqli_fetch_array($result)){
$clientid = $row['clientid'];
$clientname = $row['clientname'];
$clientno = $row['clientno'];
$clientemail = $row['clientemail'];
$clientadd = $row['clientadd'];
}
if(isset($_POST['submit'])){
$clientid = $row['clientid'];
$clientname = $row['clientname'];
$clientno = $row['clientno'];
$clientemail = $row['clientemail'];
$clientadd = $row['clientadd'];
$sql = "UPDATE client SET clientid='$clientid',clientname='$clientname',clientno='$clientno',clientemail='$clientemail',clientadd='$clientadd' WHERE clientid='$clientid'";
$result = mysqli_query($conn,$sql) or die ("Error in query: $query. ".mysqli_error());
if($result){
echo "<table><td><tr><h4>Record has been updated successfully!<br></tr></td></h4></table>";
}
else {
echo "<h4>Record has <b>NOT</b> been updated successfully<br></h4>";
}
}
?>
<form action="" method="post">
<table class ="table1">
<tr>
<td>Client ID:</td> <td><input type="text" name="clientid" size="50" value="<?php echo $clientid;?>"></td>
</tr>
<tr>
<td>Client Name:</td> <td><input type="text" name="clientname" size="50" value="<?php echo $clientname;?>"></td>
</tr>
<tr>
<td>Client Phone No.:</td> <td><input type="text" name="clientno" size="50" value="<?php echo $clientno;?>"></td>
</tr>
<tr>
<td>Client Email:</td> <td><input type="text" name="clientemail" size="50" value="<?php echo $clientemail;?>"></td>
</tr>
<tr>
<td>Client Address:</td> <td><input type="text" name="clientadd" size="50" value="<?php echo $clientadd;?>"></td>
</tr>
<td><input type="submit" value="Update" name="submit"> <input type="button" value="View" name="view" onclick='location.href="viewclient.php"'></td>
</table>
</form>
Maybe I'm stupid or what but I've been trying to figure out the problem for 3 hours and I'm this close to crying lol. Been reading all the threads here about updating form but still, no answer. Hope that anyone here could help me. Thank you.
The code you use for the client table update uses this code:
if(isset($_POST['submit'])){
$clientid = $row['clientid']; // $row should be $_POST
$clientname = $row['clientname']; // $row should be $_POST
$clientno = $row['clientno']; // $row should be $_POST
$clientemail = $row['clientemail']; // $row should be $_POST
$clientadd = $row['clientadd']; // $row should be $_POST
But those $rows should be $_POST, else the updated data will be the same as the previous data (since $row is the result from the query SELECT * FROM client WHERE clientid='$clientid'). You do it correctly in the staff table update code:
if(isset($_POST['submit'])){
$staffname = $_POST['staffname'];
$staffemail = $_POST['staffemail'];
$staffphone = $_POST['staffphone'];
Please note that your your script is at risk of SQL Injection Attack. Have a look at what happened to Little Bobby Tables. Even if you are escaping inputs, its not safe!. Use prepared parameterized statements instead.

Having trouble getting my mysql table to update

This is the form I use to edit my table:
<?php
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database...
$sql = "SELECT * FROM chart WHERE id='$id'";
$result = $conn->query($sql);
// Output the loop...
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) { ?>
<form action="./include/update.php" method="post">
<tbody>
<tr>
<td><input type="date" id="date" name="date" value="<?php echo $row['date']; ?>" /></td>
<td><input type="text" id="nuvolog_am" name="nuvolog_am" value="<?php echo $row['nuvolog_am']; ?>" /></td>
<td><input type="text" id="nuvolog_noon" name="nuvolog_noon" value="<?php echo $row['nuvolog_noon']; ?>" /></td>
<td><input type="text" id="nuvolog_pm" name="nuvolog_pm" value="<?php echo $row['nuvolog_pm']; ?>" /></td>
<td><input type="text" id="predisone" name="predisone" value="<?php echo $row['predisone']; ?>" /></td>
<td><input type="text" id="norvase" name="norvase" value="<?php echo $row['norvase']; ?>" /></td>
<tr>
<td colspan="17"><input type="text" id="symptoms" name="symptoms" value="<?php echo $row['symptoms']; ?>" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="17"><input type="submit" value="Add Records"></td>
</tr>
</tfoot>
</form>
<? }
} else {
echo "0 results";
}
// Close the connection...
mysqli_close($link);
?>
And this is the update.php
<?php
// Database credentials...
$servername = "localhost";
$username = "...";
$password = "...";
$dbname = "...";
// Database connection...
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection...
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// update data in mysql database
$sql="UPDATE chart SET
id = '$id',
date = '$date',
nuvolog_am = '$nuvolog_am',
nuvolog_noon = '$nuvolog_noon',
nuvolog_pm = '$nuvolog_pm',
predisone = '$predisone',
norvase = '$norvase'
WHERE id='$id'";
$result=mysql_query($sql);
// When chart is submitted...
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
// Close the connection...
mysqli_close($link);
?>
It's probably something very simple, but I cannot figure out why this won't update the records database. I'm hoping somebody can help me figure this out.
Please replace $result=mysql_query($sql); to mysqli code.
like
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
$conn->query($sql);
to run query use this
$conn->query($sql);
You are updating the table using $result=mysql_query($sql); while to connect you used $conn = new mysqli($servername, $username, $password, $dbname);
By the way you should delete this question (if it's possible) or change all your passwords if the password that appears in the old version is used for other accounts too (you can see the edit history).

fetch data from db and compare with user inputs

i am creating a code for email confirmation link. user inserted email id , n stores in db. Next time when user insert id into form, first of all it will check whether email id is already present in db or not. If y then said 'already exists' & if n then insert it into db. Initially i am inserting data into db. then i want to compare user input email is with db email id. so i dont know how i retrieve data on pg then compare it. here is my code
<html>
<body>
<form name="form" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" required pattern="[a-zA-Z]+" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" required pattern="[a-zA-Z]+" /></td>
</tr>
<tr>
<td>Email Id</td>
<td><input type="email" name="mail" required /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
<?php
include 'connection.php';
if(isset($_POST["submit"]))
{
$fname="'".trim(addslashes($_POST["fname"]))."'";
$lname="'".trim(addslashes($_POST["lname"]))."'";
$email="'".trim(addslashes($_POST["mail"]))."'";
$key="'".MD5(microtime())."'";
$to=$email;
$subject="Confirm your email id";
$message="Hello $fname
Click on below link to confirm your id.
www.vs.com/abcdefghojklmnopqrstuvwxyz.php?code=$key
";
$header="From :sneha#valencynetworks.com";
// echo $fname."<br />".$email."<br />".$to."<br />".$subject."<br />".$message."<br />".$header;
if(mail($to,$subject,$message,$header))
{
$sql="insert into confirm_emailid values($email,$fname,$lname,$key,'1')";
if(mysqli_query($con,$sql))
{
die("Check your id for confirmation".mysqli_error($con));
}
}
/*$sql1=mysqli_query($con,"select * from random_key where eid=$email");
while($row=mysqli_fetch_assoc($sql1))
{
echo $row['eid'];
}*/
$result="SELECT count(eid) as number_of_occurences FROM confirm_emailid WHERE eid = $_POST['mail']";
if ($row['number_of_occurences'] == 0) {
echo "this adresse isn't in the database, so add it !";
}
else {
echo "already in the database :(";
}
mysqli_close($con);
}
?>
</body>
</html>
The best way is to use Ajax for compare this email field with database emails.
Steps :
List item
On focusout from email field call ajax request
This ajax request fields contain user entered email
on php page its checks whether email exists o not if exists it gives false flag and if not it gives true flag.
4.From this method you can check email without page loading.
When your form is submited, you have an array $_POST.
So, you just have to select from your database the sames values : exemple :
SELECT count(id) as number_of_occurences FROM member WHERE mail_adresse = $_POST['e-mail'] ;
You fetch the data like you did other times, and just compare $row['number_of_occurences'] to 0.
if ($row['number_of_occurences'] == 0) {
this adresse isn't in the database, so add it !
}
else {
already in the database :(
}
index.php
<html>
<body>
<form name="form" method="post" action="process.php">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" required pattern="[a-zA-Z]+" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" required pattern="[a-zA-Z]+" /></td>
</tr>
<tr>
<td>Email Id</td>
<td><input type="email" name="mail" required /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
</body>
process.php
<?php
$host = "localhost";
$user = "root";
$password = "yourpass";
$database = "your database name";
// Establish server connection and select database
$dbh = mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_errno()) {
die('Unable to connect to database ' . mysqli_connect_error());
} else {
// run query to fetch records
// $result = mysqli_query($dbh, "SELECT email_address FROM users ");
/* fetch associative array */
$email = $_POST['mail'];
$query = "SELECT `eid` FROM `confirm_emailid` WHERE `eid` = '$email'";
$result = mysqli_query($dbh, $query); //$link is the connection
if (mysqli_num_rows($result) > 0) {
die('email already exists');
} else {
$query = mysqli_query($dbh, "insert into users(email_address) values('$email')");
echo 'data inserted succesfully';
}
}

Read and Write to SQL Database

I have the script that will write info to the database, but how can I have it print the variable "time" from the database after it updated the same query based on the email entered to write to database? This is for use with JSON.
<?php
if(!empty($_POST))
{
$dbhost = 'localhost';
$dbuser = 'casaange_testapp';
$dbpass = 'testapp1';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('casaange_volunteertest');
$email= $_POST['email'];
$time= $_POST['time'];
$sql = "UPDATE users SET time= '$time' WHERE email = '$email'";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
if($retval){
$response["success"] = 1;
$response["message"] = "Update successful!";
die(json_encode($response));
}
//echo '{"success":1, "message":"Time added!"}';
mysql_close($conn);
}
else
{
?>
<form method="post" action="timeinsert.php">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Email:</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td width="100">Time:</td>
<td><input name="time" type="text" id="time"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
I think what you want to know is whether the UPDATE query actually changed the value in the database?
You can use mysql_affected_rows() see how many rows changed as a result of your query - in your case it will be either 1 or 0.
If you need to return the time that you just put into the database, you can query the value that actually went into the database by selecting it back out with the email address as the key.
A few general observations about your code, if I may:
You must escape that POST data before putting it into an SQL query
like that. At best it'll be a source of bugs, worst a massive
security hole.
If you're writing new code, as you appear to be here, you should
consider using the newer MySQLi or PDO_MySQL extensions instead of
the old MySQL calls.
You can use json_encode to turn an associative PHP array into a JSON
object, instead of building a JSON string yourself.

Categories