updating table entry from edit button - php

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.

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!

Add Edit Delete form not adding into MySQL no errors

I have this Add Edit Delete form, the problem is:
when I put everything and I click on ADD it says "Data added successfully." but the data isn't in my table of phpAdmin and it not shows in the page...
Or is simply because my hoster doens't work with MySQLi but with MySQL?
Without talking about SQL Injections because Im not so expert and dont know how protect from that, this pages will be protected with login area so only restricted members will access to it.
index.php
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT * FROM `user` ORDER BY id DESC"); // using mysqli_query instead
?>
<html>
<head>
<title>Homepage</title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Steam Username</td>
<td>Steam Password</td>
<td>Steam Guard Code</td>
<td>Update</td>
</tr>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['steamUE']."</td>";
echo "<td>".$res['steamPW']."</td>";
echo "<td>".$res['steamGC']."</td>";
echo "<td>Edit | Delete</td>";
}
?>
</table>
</body>
</html>
add.html
<html>
<head>
<title>Add Data</title>
</head>
<body>
Home
<br/><br/>
<form action="add.php" method="post" name="form1">
<table width="25%" border="0">
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamUE"></td>
</tr>
<tr>
<td>Steam Password</td>
<td><input type="text" name="steamPW"></td>
</tr>
<tr>
<td>Steam Guard Code</td>
<td><input type="text" name="steamGC"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Add"></td>
</tr>
</table>
</form>
</body>
</html>
edit.php
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update']))
{
$id = mysqli_real_escape_string($mysqli, $_POST['id']);
$steamUE = mysqli_real_escape_string($mysqli, $_POST['steamUE']);
$steamPW = mysqli_real_escape_string($mysqli, $_POST['steamPW']);
$steamGC = mysqli_real_escape_string($mysqli, $_POST['steamGC']);
// checking empty fields
if(empty($steamUE) || empty($steamPW) || empty($steamGC)) {
if(empty($steamUE)) {
echo "<font color='red'>Steam Username field is empty.</font><br/>";
}
if(empty($steamPW)) {
echo "<font color='red'>Steam Password field is empty.</font><br/>";
}
if(empty($steamGC)) {
echo "<font color='red'>Steam Guard Code field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE `user` SET steamUE='$steamUE',steamPW='$steamPW',steamGC='$steamGC' WHERE id='$id'");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM `user` WHERE id='$id'");
while($res = mysqli_fetch_array($result))
{
$steamUE = $res['steamUE'];
$steamPW = $res['steamPW'];
$steamGC = $res['steamGC'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamUE" value="<?php echo $steamUE;?>"></td>
</tr>
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamPW" value="<?php echo $steamPW;?>"></td>
</tr>
<tr>
<td>Steam Guard Code</td>
<td><input type="text" name="steamGC" value="<?php echo $steamGC;?>"></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>
</body>
</html>
delete.php
<?php
//including the database connection file
include("config.php");
//getting id of the data from url
$id = $_GET['id'];
//deleting the row from table
$result = mysqli_query($mysqli, "DELETE * FROM `user` WHERE id='$id'");
//redirecting to the display page (index.php in our case)
header("Location: index.php");
?>
add.php
<html>
<head>
<title>Add Data</title>
</head>
<body>
<?php
//including the database connection file
include_once("config.php");
if(isset($_POST['Submit'])) {
$steamUE = mysqli_real_escape_string($mysqli, $_POST['steamUE']);
$steamPW = mysqli_real_escape_string($mysqli, $_POST['steamPW']);
$steamGC = mysqli_real_escape_string($mysqli, $_POST['steamGC']);
// checking empty fields
if(empty($steamUE) || empty($steamPW) || empty($steamGC)) {
if(empty($steamUE)) {
echo "<font color='red'>Steam Username field is empty.</font><br/>";
}
if(empty($steamPW)) {
echo "<font color='red'>Steam Password field is empty.</font><br/>";
}
if(empty($steamGC)) {
echo "<font color='red'>Steam Guard Code field is empty.</font><br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} else {
// if all the fields are filled (not empty)
//insert data to database
$result = mysqli_query($mysqli, "INSERT INTO `user` (steamUE,steamPW,steamGC) VALUES ('$steamUE','$steamPW','$steamGC')");
//display success message
echo "<font color='green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}
?>
</body>
</html>
config.php
<?php
/*
// mysql_connect("database-host", "username", "password")
$conn = mysql_connect("localhost","root","root")
or die("cannot connected");
// mysql_select_db("database-name", "connection-link-identifier")
#mysql_select_db("test",$conn);
*/
/**
* mysql_connect is deprecated
* using mysqli_connect instead
*/
$databaseHost = 'sql.website.com';
$databaseName = '';
$databaseUsername = '';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
It not doesn't says or shows any errors or any other problems, it says only data added successfully and nothing else. I don't understand why it doesn't add any data in my tables, i checked everything again and again, maybe because i'm tired but i tried to rename tables names but nothing change, is the same...
Spotted three errors,
add.php: Column names should be without ''. Check the following
$result = mysqli_query($mysqli, "INSERT INTO user (steamUE,steamPW,steam_GC) VALUES ('$steamUE','$steamPW','$steamGC')");
edit.php: '' missing from $id. Check the following
$result = mysqli_query($mysqli, "UPDATE user SET steamUE='$steamUE',steamPW='$steamPW',steamGC='$steamGC' WHERE id='$id'");
delete.php: '' missing from $id. Check the following
$result = mysqli_query($mysqli, "DELETE * FROM user WHERE id='$id'");
If the connection with DB is successful, it must work (and this answer deserves a green tick from you :D).
Or is simply because my hoster doens't work with MySQLi but with
MySQL?
Wherever I faced issues, I got some error or a blank page.
Check your dB connection. Turn to mysqli, declair it with $sql with (errno), but call your param before $sql. Use if condition to check your connection. On your add please use prepared with $stmnt and execute it.

I am trying to create e dynamic table where data will be fetched and I can edit any value I want

I can fetch the data but the submit button is not working.
I am confused with the update query and storing data in array.
Here is the code for fetching and showing data in table.
`<?php
while ($rows=mysqli_fetch_assoc($result)){ ?>
<tr>
<td align="center">
<?php $id[]=$rows['id']; ?><?php echo $rows['id']; ?>
</td>
<td align="center">
<input name="name[]" type="text" id="name" value="<?=$rows['name']; ?>">
</td>
<td align="center">
<input name="lastname[]" type="text" id="lastname" value="<? =$rows['lastname']; ?>">
</td>
<td align="center">
<input name="email[]" type="text" id="email" value="<?=$rows['email']; ?>">
</td>
</tr>
`
Here is the code for submit button
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_POST["Submit"] != ""){
$count = mysqli_num_rows($result);
for($i=0;$i<$count;$i++){
$sql2="UPDATE test_mysql SET name='".$_POST["name"][$i]."',lastname='".$_POST["lastname"][$i]."', email='".$_POST["email"][$i]."' WHERE id='$id[$i]'";
$result1=mysqli_query($con, $sql2);
}
header("Location: update-multiple-2.php");
}
If you handle POST after outputting form (to set variable $id) and variable $test_mysql is set to existing table in your database and all columns exists and you are only one who can add or remove row (because it will change the $id variable) then it should work.
Maybe this could help:
if(!$result1=mysqli_query($con, $sql2)){
echo 'Error: '.mysqli_error();
}
You need to debug it somehow:
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_POST["Submit"] != ""){
$count = mysqli_num_rows($result);
$error = '';
for($i=0;$i<$count;$i++){
$sql2="UPDATE $test_mysql SET name='".$_POST["name"][$i]."',lastname='".$_POST["lastname"][$i]."', email='".$_POST["email"][$i]."' WHERE id='$id[$i]'";
if(mysqli_query($con, $sql2) === FALSE){
$error .= 'SQL query failed, SQL: '.$sql2.', Error: '.mysqli_error() . "\n";
}
}
if(!$error){
header("Location: update-multiple-2.php");
}else{
echo $error;
exit();
}
}

MySQL UPDATE query problems

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?

form echoes success without submittting anything to database. Is there something wrong with my flow control?

Here is the code.
I really dont why it is not submitting my information.
<?php
//Includes mass includes containing all the files needed to execute the full script
//Also shows homepage elements without customs
include ("includes/mass.php");
//Grabbing data form POST array and storing in variables plus the date
$username = ($_POST['username']);
$password = ($_POST['password']);
$conpassword= ($_POST['password2']);
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$email = ($_POST['email']);
$submit = ($_POST['submit']);
$date = date("Y-m-d");
//Reigstration Form
$register = "<div id='registration'>
<h2>Register Here!</h2>
<form action='register.php' method='post'>
<table>
<tr>
<td>
Username
</td>
<td>
<input type='text' name='username' value='$username' >
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<input type='password' name ='password'>
</td>
</tr>
<tr>
<td>
Confirm Password
</td>
<td>
<input type='password' name ='password2'>
</td>
</tr>
<tr>
<td>
Firstname
</td>
<td>
<input type='text' name='firstname' value='$firstname'>
</td>
</tr>
<tr>
<td>
Lastname
</td>
<td>
<input type='text' name='lastname' value='$lastname' >
</td>
</tr>
<tr>
<td>
Email
</td>
<td>
<input type='text' name='email' value= '$email' >
</td>
</tr>
<tr>
<td>
<input type='submit' class='button' name='submit' value='Sign Up'>
</td>
</tr>
</table>
</form>
</div>";
echo $register;
//Check to make sure user has submitted the correct details
echo "<div id='regform'>";
if (isset($submit))
{
//Querying the database for if the username already exists
$sql = "SELECT * FROM user WHERE username = '$username'";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if (strlen($username)<2)
{
echo ("<br>You must enter a longer username</br>");
exit;
}
elseif (strlen($username) > 25)
{
echo ("You must enter a shorter username<br>");
exit;
}
if ($username==$dbusername)
{
echo ("That username already exists!");
exit;
}
elseif (strlen($password)<6)
{
echo ("<br>'Password must be be between 6 & 26 characters'<br>");
exit;
}
if ($password != $conpassword)
{
echo ("<br>Your passwords dont match<br>");
exit;
}
elseif (strlen($firstname)<=0)
{
echo ("<br>You must enter your firstname<br>");
exit;
}
if (strlen($lastname)<=0)
{
echo ("<br>You must enter your lastname<br>");
exit;
}
elseif (!preg_match('/#/',$email) || (strlen($email)<=6) )
{
echo ("</br>You must enter a proper email address!");
exit;
}
if (!isset($password))
{
echo "You must enter a password!";
exit;
}
elseif (!isset($conpassword))
{
echo ("You must confirm your password");
exit;
}
else
{
//Encrypt the password
$password = md5($password);
$conpassword = md5($conpassword);
//Start Session
session_start();
//push this information to the database
//Submit data to database plus store exec into variable.
$sqlsubmit ="INSERT INTO user VALUES ('','$firstname','$lastname','$username','$password','$email','$date',)";
mysql_query($sqlsubmit);
//echo success.
echo "successfully submitted to the database"."<br>"."<a href='user.php'>Click Here To Go To Your Accont</a>";
exit;
}
}
elseif(!isset($submit))
{
echo "</br>"."Enter your info here!!!!! :))";
}
echo "</div>";
?>
It has been state by Pekka as well as in a comment... but since this is very important, I'll repeat it in a separate (community wiki) answer:
This code is vulnerable to SQL-injection attacks of the worst kind.
Your code is absolutely insecure. It should not be used, no excuses possible. Go read about SQL-Injection and input sanitisation before you proceed any further.
http://xkcd.com/327/
Update: As Quassnoi so subtly points out, you urgently need to secure your input. See the chapter SQL Injection in the PHP manual.
The query fails because you have an extra comma at the end of the line:
$sqlsubmit ="INSERT INTO user VALUES
('','$firstname','$lastname','$username','$password','$email','$date',)";
Use echo mysql_error(); to find out such errors.
Also, the success message gets output, regardless whether the query fails or not.
You want to add a condition:
if (mysql_query($sqlsubmit))
echo "successfully submitted ...";
else
echo "error submitting ..... ".mysql_error();

Categories