I have a super easy question. I have a form that echoes out a mySQL record that the user can update. I make my changes, and it tells me that the update is successful, but when I look at the table, the changes do not go through. What is the problem here?
This is the first script.
<?php
require_once("models/config.php");
?>
<table border=1>
<tr>
<td align=center>Edit Form</td>
</tr>
<tr>
<td>
<table>
<?
$personid=$_SERVER['QUERY_STRING'];
$order = "SELECT * FROM persons where personid='$personid'";
$result = mysqli_query($mysqli,$order);
$row = mysqli_fetch_array($result);
?>
<form method="post" action="edit_data.php">
<input type="hidden" name="id" value="<? echo "$row[personid]"?>">
<tr>Person ID:<? echo "$row[personid]"?></tr>
<tr>
<td>First Name</td>
<td>
<input type="text" name="firstname"
size="20" value="<? echo "$row[firstname]"?>">
</td>
</tr>
<tr>
<td>Surname</td>
<td>
<input type="text" name="surname" size="40"
value="<? echo "$row[surname]"?>">
</td>
</tr>
<tr>
<td align="right">
<input type="submit"
name="submit value" value="Edit">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
Which then goes through to this:
<?
require_once("models/config.php");
$personid = $_POST['personid'];
$firstname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['firstname']));
$surname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['surname']));
$order = "UPDATE persons SET firstname='$firstname', surname='$surname' WHERE personid='$personid'";
$result = mysqli_query($mysqli,$order);
if (!$result) {
echo "Error entering data! <BR>";
echo mysql_error();
} else {
echo "User updated to $firstname $surname <BR>";
}
?>
Is there something I am missing here?
Thanks in advance.
You are sending a hidden input named id and trying to use a $_POST['personid']
correct that
You may also pay attention to the comments you had (SQL Injection's one at least)
Your form sends the id in the field id, while you refer to it as personid.
The reason why this appears to be working, is that the update in itself is correct. $personid is treated as an empty string, so the update correctly updates all records that have an empty personid, which is no record at all.
OK, so here is a revised script with prepared statements. The script is working in the sense that updates are being made to the records. Two questions:
1) is this safe from My-SQL injections?
2) This is updating records successfully, but now it is echoing out "Error entering data!", how come?
<?
require_once("models/config.php");
$personid = $_POST['personid'];
$firstname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['firstname']));
$surname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['surname']));
$order = "UPDATE persons SET firstname=?, surname=? WHERE personid=?";
$stmt = mysqli_prepare($mysqli, $order);
mysqli_stmt_bind_param($stmt, "ssi", $_POST['firstname'], $_POST['surname'], $_POST['personid']);
mysqli_stmt_execute($stmt);
$result = mysqli_query($mysqli,$stmt);
if (!$result) {
echo "Error entering data! <BR>";
echo mysqli_error($mysqli);
} else {
echo "User updated to $firstname $surname <BR>";
}
?>
I'm sure the second question is a rather boneheaded one - do I just reverse the conditions?
Related
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!
I am going to fetching table values in a html table along checkbox in each row and then inserting values in another database table from multi check boxes in php.
Only the values of checked boxes should be submitted to that table.
db name "laboratory":
test: fetching values.
package: inserting table.
view
Status
Active
Inactive
<?php
$conn=mysqli_connect("localhost","root","","laboratory") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
Please try to follow this code and implement in your program . Hope that this will cooperate you much
if(isset($_POST['name'])){
$name = $_POST['name'];
$status = $_POST['status'];
if(empty($name) || empty($status)){
echo "Field Must Not be empty";
} else{
$conn=new mysqli("localhost","root","","test");
if($conn){
$query = "SELECT * FROM userdata limit 5";
$stmt = $conn->query($query);
$val = '<form action="" method=""> ';
$val .= '<table> ';
if ($stmt) { ?>
<form action="" method="post">
<table>
<?php while ($result=$stmt->fetch_assoc()) { ?>
<tr>
<td><?php echo $result['post']; ?></td>
<td><input value="<?php echo $result['post']; ?>" type="checkbox" name="check[]" /></td>
</tr>
<?php } ?>
<tr>
<td>Actual Price </td>
<td>Discount</td>
<td>Final Price</td>
</tr>
<tr>
<td><input type="text" name="actual"/></td>
<td><input type="text" name="discount"/></td>
<td><input type="text" name="final"/></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" id="" cols="30" rows="10"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Cancel" /></td>
</tr>
</table>
</form>
<?php }} }}?>
<?php
if(isset($_POST)){
echo "<pre>";
print_r($_POST);
echo "<pre>";
}
?>`enter code here`
First of all you have to decide that what are you using either mysqli or mysql, if you are using mysqli then you have to improve your code
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
and when you want to insert the checked data will be inserted in package table. If package table in another database then you have to give us the full detail i mean tell us the database name of package table.
Can anyone tell me where my problem is here, this page is linked from edit buttons I have embedded on a table of all entries. However, it is entering the current data into the fields and not updating when I enter new values? Any help appreciated.
php:
<?php
include_once("config.php");
date_default_timezone_set('Europe/London');
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$EditQuery = "SELECT * FROM ACW WHERE UserID=$id";
$results = sqlsrv_query ($conn, $EditQuery);
while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
{
$firstname = $row['FirstName'];
$lastname = $row['LastName'];
$location = $row['location'];
}
if(isset($_POST['update']))
{
$id = $_POST['UserID'];
$firstname = $_POST['FirstName'];
$lastname = $_POST['LastName'];
$location = $_POST['location'];
// checking empty fields
if(empty($firstname) || empty($lastname) || empty($location)) {
if(empty($firstname)) {
echo "<font color='red'>First Name field is empty.</font><br/>";
}
if(empty($lastname)) {
echo "<font color='red'>Last Name field is empty.</font><br/>";
}
if(empty($location)) {
echo "<font color='red'>Location field is empty.</font><br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
}
if (preg_match("/^[0-9-]+$/",$firstname || $lastname || $location)) {
echo "<font color='red'>Numbers are not valid in these fields</font><br/>";
}
} else {
//updating the table
$UpdateQuery ="UPDATE ACW SET FirstName='$firstname', LastName='$lastname', location='$location' WHERE UserID='$id'";
echo $UpdateQuery;
//echo "<font color='green'>Data has been updated.</font><br/>";
$results = sqlsrv_query ($conn, $UpdateQuery);
}
?>
form:
<form name="form1" method="get" action="edit.php">
<table border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="firstname" value="<?php echo $firstname;?>"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastname" value="<?php echo $lastname;?>"></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="location" value="<?php echo $location;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
I suggest you make 3 changes:
1.0 Give the form inputs different variable names to the one collected from the database( e.g instead of $firstname give but say $firstname_form)
2.0 Your form has method as GET but you are using POST to update
3.0 Your form action page is edit.php but the fact that you are collecting the item id via GET means that your edit button must be linked to a certain edit.php?id=$item_id Hence the action page should be edit.php?id=$id
c/o your comment: Yes. Exactly what I imagined. So, for your form action replace edit.php with edit.php?id=<?php if(isset($id)){ echo $id; } ?> You are saying that, if the id exist on this page display it as paramater.
I wasn't asking for your link button to be changed. It is correct. To prove that it is correct, echo the id at your edit page like this
if(isset($_GET['id'])){
$id = $_GET['id'];
echo $id;
exit();
}
You can then comment or remove the echo and exit lines after confirming that the id is passed to the edit page.
Now, on your form I was saying that the action should look like this
<form action="edit.php?id=<?php if(isset($id)){ echo $id; } ?>" method="GET" name="form1">
</form>
Adjust the variable names as I suggested earlier as well as changing input verification from POST to GET. Your database should now be updated.
I'm trying to create a form which allows you to update a database table using php.
I'm kinda new to PHP so excuse me if I make a stupid mistake in the code.
This is my edit.php code:
<html>
<head>
</head>
<body>
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM cats");
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<?php
while($row = mysqli_fetch_array($result))
{
$name = $row['name'];
$email = $row['email'];
$rank = $row['rank'];
$birth = $row['birth'];
$joined = $row['joined'];
$steamid = $row['steamid'];
?>
<td width="100"></td>
<td><?=$name?></td>
</tr>
<tr>
<td width="100">Email</td>
<td><input name="emailid" type="text" value="<?=$email?>"></td>
</tr>
<tr>
<td width="100">Rank</td>
<td><input name="rankid" type="text" value="<?=$rank?>"></td>
</tr>
<tr>
<td width="100">Birth</td>
<td><input name="birthid" type="text" value="<?=$birth?>"></td>
</tr>
<tr>
<td width="100">Joined</td>
<td><input name="joinedid" type="text" value="<?=$joined?>"></td>
</tr>
<tr>
<td width="100">Steamid</td>
<td><input name="steamidid" type="text" value="<?=$steamid?>"></td>
</tr>
<?php } ?>
<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
if(isset($_POST['update']))
{
$name = $row['nameid'];
$email = $row['emailid'];
$rank = $row['rankid'];
$birth = $row['birthid'];
$joined = $row['joinedid'];
$steamid = $row['steamidid'];
$update = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
$retval = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
}
echo "Updated data successfully\n";
}
mysqli_close($con);
?>
</body>
</html>
It shows the table and information but the updating isn't working.
Updated data successfully
I've checked the database but it's not updating anything.
Dear i think you change the record based on Name because you can use $name in where clause and you can also change the Name than never true where clause so that your query execute successfully but not effected on any of the row.
you want to get for editable record and that's unique id base update row it will defiantly work.
Try to use PHP PDO database access functions, your code as it stands is vulnerable to SQL-Injection! PDO will also make debugging and working with the database much easier.
I think your check for "update" in $_POST is not working because update is not a field inside your form but the submit button itself, try to check for one of the fields instead.
Informations:
With mysqli_error() you need to write about which connection you want to get errors, like this:
mysqli_error($con);
With mysqli_query() you need to give two parameters, connection and query like this:
$update = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
How to debug:
If you want to check that UPDATE query return any error you can do something like this:
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
}
You can try to debug your query with something like this:
$sql = "UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';";
echo $sql; // this output write in your phpMyadmin to check if there are any errors.
$update = mysqli_query($con, $sql);
Other problem we got:
1. I think also you should have else in your code, f.ex.:
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
} else {
echo "Updated data successfully\n";
}
2. You are not getting data from $_POST it should be like:
$name = $_POST['nameid']; // not $row['nameid']
$email = $_POST['emailid'];
$rank = $_POST['rankid'];
$birth = $_POST['birthid'];
$joined = $_POST['joinedid'];
$steamid = $_POST['steamidid'];
More about used functions:
PHP: mysqli::$error
PHP: mysqli::query
In your case it is Procedural style
I have been working on a project and i am at the final stages of the project. My problem is whenever i try to update data in my database table into returns a blank screen with no error messages. Please find the php script and html form (the form responsible for updating the database table) below, i have divided it into about four sections:
Thanks in advance
Update Form:
<a name="inventoryEditForm" id="inventoryEditForm"></a>
<h3>↓Add New Question Form↓</h3>
<form action="inventory_edit.php" enctype="multipart/from-data" name="myForm" id="myForm" method="post">
<table width="80%" border="0" cellspacing="3" cellpadding="7">
<tr>
<td width="20%"> </td>
<td width="80%"> </td>
</tr>
<tr>
<td>Question</td>
<td><textarea rows="" name="question" cols=""><?php echo $question; ?></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Venue</td>
<td><input type="text" name="venue" maxlength="50" value="<?php echo $venue; ?>"></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="questiondate" value="<?php echo $date; ?>"></td>
</tr>
</table>
<br>
<input name="thisID" type="hidden" value="<?php echo $targetID; ?>"/>
<input type="submit" name="submit" value="Update Question">
<input type="reset" name="clear" value="Clear Form">
</form>
PHP Script:
<?php
//Error reporting due to long script
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
error_reporting(E_PARSE);
//Update question table
If (isset($_POST['question'])) {
$id = mysqli_real_escape_string($link, $_POST['thisID']);
$question = mysqli_real_escape_string($link, $_POST['question']);
$venue = mysqli_real_escape_string($link, $_POST['venue']);
$date = mysqli_real_escape_string($link, $_POST['questiondate']);
//Update question in the table
$sql = mysqli_query($link, "UPDATE DebateQuestion SET question='$question',venue='$venue',date='$date' WHERE qQuestionNo='$id'LIMIT 1") or die(mysql_error());
header("location: inventory.php");
exit();
}
?>
<?php
error_reporting(E_PARSE);
//Gather this questions full information and insert automatically into the edit form
if (isset($_GET['qid'])) {
$targetID = $_GET['qid'];
$sql = mysqli_query($link, "SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1") or die(mysql_error());
$questionCount = mysqli_num_rows($sql); // count the output amount
if ($questionCount > 0) {
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
$id = $row["qQuestionNo"];
$question = $row["qQuestion"];
$venue = $row["qDebateVenue"];
$date = strftime("%b %d, %Y", strtotime($row["qDate"]));
}
} else {
echo "Oops, no questions like that exists. Check <a href='inventory.php'>inventory</a>again";
exit();
}
}
?>
In your update query you have the data column without using ` back ticks , date is also a mysql's function try to wrap up your column names with back ticks if you are not sure whether they conflict with mysql's reserved keywords
$sql = mysqli_query($link,"UPDATE DebateQuestion SET
`question`='$question',`venue`='$venue',`date`='$date'
WHERE qQuestionNo='$id'LIMIT 1")
"SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1"
Here is qQuestionNo column a string type?if not remove quotes around $targetID.
Note : I have not tested the code - just read it on screen.
I've never seen an IF statement capitalized before :
If (isset($_POST['question'])) {
I'd guess this makes a difference however.
There's lots of other weird things going on in your files, but none that should give you white screen. Try lowercase 'I' in your if statement first.
ALSO - re: the UPDATE statement, you are missing a space between the $id and the LIMIT :
**qQuestionNo='$id'LIMIT 1**