Display and update MYSQL data via HTML form via PHP - 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.

Related

php page to list and update sqlite

I have the following code to display and modify a simple sqlite table
<?php
$db = new SQLite3("my_sqlite.db");
$query = "SELECT rowid, * FROM students";
$result = $db->query($query);
if( isset($_POST['submit_data']) ){
// Gets the data from post
$name = $_POST['name'];
$email = $_POST['email'];
$query = "UPDATE students set name='$name', email='$email'";
if( $db->exec($query) ){
echo "Data is updated successfully.";
}else{
echo "Sorry, Data is not updated.";
}
}
?>
<table border="1">
<form action="" method="post">
<tr>
<td>Name</td>
<td>Email</td>
</tr>
<?php while($row = $result->fetchArray()) {?>
<tr>
<td><input name="name" type="text" value="<?php echo $row['name'];?>"></td>
<td><input name="email" type="text" value="<?php echo $row['email'];?>"></td>
</tr>
<?php } ?>
<input name="submit_data" type="submit" value="Update Data">
</form>
</table>
PROBLEM: When I change some of the information and update, the whole column changes into the same change. E.g.: if I write a the name Nick, every name changes into Nick.
First, you should only do updates for one record at a time so each record needs its own update button. Attached is the corresponding rʔwid of the record. you can use:
<input type="hidden" name="rowid" value="$row['rowid]">
You should add a WHERE clause to the update statement to know exactly which records should be updated.If you omit the WHERE clause, ALL records will be updated!

Displaying SQL data in HTML form

I wrote following code in PHP to get the details from the mysql table but I dont know how to display them in HTML form.
<?php
$servername = "localhost";
$username = "root";
$password = "icsk";
$dbname = "yusuf";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT dsl, Fname, Lname, Cid, pack FROM homereg";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['dsl']. " " . $row['Fname']. " " . $row['Lname']. " " . $row['cid']. " " . $row['pack'] ."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The above code displays the data on the webpage with the help of echo but i want it to be displayed in form.
HTML form has following code:
<form method="POST" name = "frm" action="homerenew.php">
<div align="center">
<table border="1" width="425">
<tr>
<td width="223"><font face="Georgia"><b>Subscription Number</b></font></td>
<td width="186"><input type="text" name="T1" size="20"></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Your Current Pack</b></font></td>
<td width="186"><input type="text" name="T2" size="20"></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Renewal Options</b></font></td>
<td width="186"><select size="1" name="D1">
<option value = "1 Month">1 Month</option>
<option value = "2 Months">6 Months</option>
<option value = "1 Year>1 Year</option>
</select></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Balance Payable</b></font></td>
<td width="186"><input type="text" name="T3" size="20"></td>
</tr>
</table>
</div>
<p align="center"><input type="submit" value="Renew" name="B1">
<input type="reset" value="Reset" name="B2"></p>
</form>
I am new to PHP connectivity that is why little confused. Help will be greatly appreciated. Thank you
First of all you need to have .php extension of the page containing your HTML form.
After fetching data from database you could set it into form element like
<input type="text" name="T1" size="20" value="<?php echo $row['dsl'];?>">
I would recomend using a templating engin similar to PHPTal. You write your html page as an .xhtml file that contains tal: tags that are used by the template engine to insert your php values. Install instructions, example of use.
The benfit of using a template engine is you can remove all html content from your scripts and leave the display logic in the xhtml file. The php code just gathers the data and assigns it to labels your template knows about.
You can get all rows as an array and assign it to a variable name in the template object in php. That variable name is then used in the xhtml file to repeat rows in your table (or any other element).
Php:
<?php
require_once 'PHPTAL.php';
$rows = getMyDBRows();
// create a new template object
$template = new PHPTAL('my_template_file.xhtml');
$template->rows = $rows;
// execute the template
try {
echo $template->execute();
}
catch (Exception $e){
echo $e;
}
Xhtml rows section with example of repeating each row, inserting element contents, setting attributes and using a conditional statement to only display the input field for the row with index 1. Repeat method can be used for options in selects and conditional check for setting selected attribute. Phptal requires strict xhtml structure any errors in your xhtml and the page will return an error identifying where there was a problem.
<tr tal:repeat="row rows">
<td tal:content="row/dsl"><\td>
<td tal:content="row/fname"><\td>
<td><input name="lname" tal:attributes="value row/lname, style php: repeat.row.id EQ 1?'display:inline-block':'display:none" tal:content="row/lname"></input>
......
<\tr>

Hyperlink row to fetch row data in another page, PHP?

I want to fetch data of row buy clicking "apply" button in another page.
Which code should I use for hyberlink on the row?
also which code should I use for the another page which will show the row date?
This is the code I use:
<?php
/////// Update your database login details here /////
$dbhost_name = "localhost:1234"; // Your host name
$database = $CONFIG->dbname; // Your database name
$username = $CONFIG->dbuser; // Your login userid
$password = $CONFIG->dbpass; // Your password
$conn = mysql_connect($dbhost_name, $username, $password);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM jobs';
mysql_select_db($database);
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
?>
<?php
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
?>
<table border="2">
<thead>
<tr>
<td><?php echo $row['jobid']; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['company']; ?></td>
<td>
<form name="search" action="submit.php" method="POST">
<?php echo $row['jobid']; ?>
<input type="submit" value="apply" name="submit" />
</form>
</td>
</tr>
</tbody>
</table>
<?php
}
mysql_close($conn);
?>
If you want to send data from database to submit.php use hidden input type and and echo your data in the value section. Eg:
<form name="search" action="submit.php" method="POST">
<input type="hidden" name="jobid" value="<?php echo $row['jobid']; ?>" />
<input type="hidden" name="title" value="<?php echo $row['title']; ?>" />
<input type="hidden" name="company" value="<?php echo $row['company']; ?>" />
<input type="submit" value="apply" name="submit" />
And in processing page that is your submit.php use $_POST to fetch the data eg:
<?php
$jobid = $_POST['jobid'];
?>
How ever you are using mysql_* which is clearly outdated and removed from new php vevrsion. I recommend to use mqsqli or PDO. And start using prepare statements to remove the risk of sql injection.
You are describing something called AJAX. Don't be worried, it is actually quite easy.
See this example for an overview of what you want to do.
See this answer for some simple examples of AJAX to get you started.
Note that the PHP page with the AJAX javascript code, and the PHP page the AJAX sends data to, cannot be the same page. Although that is possible with <form> constructs, it is not possible with AJAX. (Instead of receiving the desired output, you will receive back the full HTML of the page)

PHP MySQL Statements not Updating Database

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;
}

PHP page is storing form input variables after user submits

I wasn't sure what else to call the title...I have a PHP page that accesses a certain MySQL database, pulls the values from the table, and places them in an HTML form (POST method - PHP_SELF). The user can then view the values, alter them as they wish, and submit them. The page then takes those values and updates the MySQL database. Everything works perfectly except that when the user submits and the page goes to show the new updated variables, it still shows the old values. The user is forced refresh the page before the new variables show up. I thought that PHP was perhaps not deleting the variables, so I unset all stored variables after the script was over and it's still not working. I ever tried putting a sleep timer before the script started, and that didn't work either. I'd appreciate any suggestions. Here is my script just for reference:
<html>
<body>
<?php
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
?>
</body>
</html>
You are displaying the data from the database before you update it.
It is normally good practice to do all your database connectivity at the top of the page, then display the results.
In your code (even if a user has submitted an update), you query the data, pull it from database and display it, then run the update with what the user submitted.
Changing your code to this should do the trick (Do read the note below though):
<html>
<body>
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
</body>
</html>
Bad note - your code is wide open to injection attacks. You are using form data with no verification. That's a big red flag. Secondly, you are using deprecated mysql_* functions. Your code should be using mysqli_* functions or better yet move to PDO. It is much safer and you will be able to do a lot more with it.
Edit 2: The page IS being updated after the user submits the form, but the page you display to the user is querying the database before you update it - and using that to display the page to the user.

Categories