There is a table:
|id name surname email |
|1 john surjohn #mail.com|
|2 peter pet #mail.com|
|.........................|
PHP:
<?php
if(isset($_POST['update']))
{
...
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$id = $_POST['id'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$mail = $_POST['mail'];
$sql = "UPDATE emps ".
"SET name= '$name', surname'$surname', email='$mail' ".
"WHERE Id = $id" ;
mysql_select_db('dbase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "blablablabla ! \n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<fieldset style="width: 350px" >
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Id </td>
<td><input name="id" type="text" id="id" value=""></td>
</tr>
<tr>
<td width="100">name</td>
<td><input type="text" maxlength="15" name="name" value="" ></td>
</tr>
<tr>
<td width="100">surname</td>
<td><input type="text" maxlength="40" name="surname" value="" ></td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="update">
</td>
</tr>
</table>
</fieldset>
</form>
<?php
}
?>
}
In this form i need update all fields otherwise, updated table can have null values.
I want for example, update name field, but leave surname, email existing values. ideas?
Could try something like this:
$id = $_POST['id'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$mail = $_POST['mail'];
$sql = "UPDATE emps SET";
$moresql = '';
if(isset($name) && !empty($name)) {
$moresql .= " name = '$name'";
}
if(isset($surname) && !empty($surname)) {
if ($moresql) $moresql .= ',';
$moresql .= " surname = '$surname'";
}
if(isset($mail) && !empty($mail)) {
if ($moresql) $moresql .= ',';
$moresql .= " mail = '$mail'";
}
$sql .= $moresql;
$sql .= " WHERE Id = '$id'";
This is untested though.
Karl's idea is the way to go, but it can be refactored this way:
$id = $_POST['id'];
$sql = "UPDATE emps SET";
$fieldValuePairs = array();
foreach($_POST as $key => value)
if($key != 'id')
$fieldValuePairs[] = "'$key' = '$value'";
$sql .= " ". implode(',', $fieldValuePairs)." WHERE id = $id";
Note: this works only if you use input names (in the form) equal the column names (in the database).
Have a great day.
Related
Hi i use this php script to update some values in my database but it accepts only numbers when i put my email it says : Could not update data: 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 '#hotmail.com' at line 1
i want to update the values where by entering email and username
and increase the values because i have more than 5 values to update
any solution? :)
<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['update'])) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$email = $_POST['email'];
$gold = $_POST['gold'];
$sql = "UPDATE userdata ". "SET gold = $gold ".
"WHERE email = $email" ;
mysql_select_db('chickenstories');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<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">Gold : </td>
<td><input name = "gold" type = "text"
id = "gold"></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>
The problem is you are not putting email as string, you are passing it without escaping it, update this line:
$sql = "UPDATE userdata ". "SET gold = $gold ". "WHERE email = $email" ;
to Be:
$sql = "UPDATE userdata ". "SET gold = $gold ". "WHERE email = '$email'" ;
I also recommend you to escape all variable before putting them in database, to avoid SQL injection.
now it dont work again i have somewhere a syntax error on my query
Could not update data: 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 'email = 'test#hotmail.com' and username = 'TestName'' at line 1
<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['update'])) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$email = $_POST['email'];
$username = $_POST['username'];
$gold = $_POST['gold'];
$chickens = $_POST['chickens'];
$sql = "UPDATE userdata ". "SET gold = $gold, chickens = $chickens". "WHERE email = '$email' and username = '$username'" ;
mysql_select_db('chickenstories');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<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">Username : </td>
<td><input name = "username" type = "text"
id = "username"></td>
</tr>
<tr>
<td width = "100">Gold : </td>
<td><input name = "gold" type = "text"
id = "gold"></td>
</tr>
<tr>
<td width = "100">Chickens : </td>
<td><input name = "chickens" type = "text"
id = "chickens"></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 am not sure why my database is not receiving information from my website. Also, no error messages are popping up so I'm not sure the data is going anywhere at all. It appears to be letting me connect to the database, but when I click add employee I just get a blank page. Any suggestions?
EDIT: I have changed my code to only input one variable, but am still only returning a blank page.
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['add'])) {
$dbhost = '';
$dbuser = 'j';
$dbpass = 'os';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$emp_name = addslashes ($_POST['employee_name']);
} else {
$emp_name = $_POST['employee_name'];
}
$sql = "INSERT INTO employee ". "(employee_name) ". "VALUES('$emp_name')";
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
} else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table width = "400" border = "0" cellspacing = "1" cellpadding = "2">
<tr>
<td width = "100">
Employee Name
</td>
<td>
<input name = "employee_name" type = "text" id = "employee_name">
</td>
</tr>
<tr>
<td width = "100">
</td>
<td>
</td>
</tr>
<tr>
<td width = "100">
</td>
<td>
<input name = "add" type = "submit" id = "add" value = "Add Employee">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
$sql = "INSERT INTO employee ". "(employee_name) ". "VALUES('$emp_name', NOW())";
You are passing 2 values in the sql, but only specifying one column. employee_name
you probably need to either remove the NOW() value or add another column (employee_name, date_added)
$sql = "INSERT INTO employee ". "(employee_name) ". "VALUES('$emp_name')";
$sql = "INSERT INTO employee ". "(employee_name, date_added) ". "VALUES('$emp_name', NOW())";
<form action="book.php" method="post">
<table>
<thead>
<tr>
<td>FlightID</td>
<td>From</td>
<td>Destination</td>
</tr>
</thead>
<tbody>
<tr>
<td name="flightID" value="1">1</td>
<td name="From" value="Sydney">Sydney</td>
<td name="Destination" value="Bali">Bali</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</tr>
<tr>
<td name="flightID" value="2">2</td>
<td name="From" value="London">London</td>
<td name="Destination" value="HongKong">Hong Kong</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</tr>
</tbody>
</table>
</form>
I created a table like this. At the end of each row, it has a book button.
What I am trying to do is when the user clicked the button, the selected row data(ID,From,Des) will pass to the 'book.php', then the PHP file will do the rest of the job.
But I tried to catch the value using $_POST['name'] in 'book.php', like this
<?php
if(isset($_POST['booking'])){
$ID = $_POST['flightID'];
$From = $_POST['From'];
$To = $_POST['Destination'];
}
?>
It shows all of those values are undefined. Any help would be appreciated.
The problem is that the values in <td> cannot be passed from the form to your PHP file by themselves. You could use hidden inputs for this. Additionally, each row in the table should be its own form to assure that all data is not submitted at the same time.
Try this:
<table>
<thead>
<tr>
<td>FlightID</td>
<td>From</td>
<td>Destination</td>
</tr>
</thead>
<tbody>
<tr>
<form action="book.php" method="post">
<td><input type="hidden" name="flightID" value="1">1</td>
<td><input type="hidden" name="From" value="Sydney">Sydney</td>
<td><input type="hidden" name="Destination" value="Bali">Bali</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</form>
</tr>
<tr>
<form action="book.php" method="post">
<td><input type="hidden" name="flightID" value="2">2</td>
<td><input type="hidden" name="From" value="London">London</td>
<td><input type="hidden" name="Destination" value="HongKong">Hong Kong</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</form>
</tr>
</tbody>
i have the same problem as yours and tried to create an answer so i came up with this code to indicate each row in an HTML table with a special name using loops, i can now take the specified row and do as much PHP operations as i can with it without disturbing the table as a whole and it was well synchronized with my database, hope it helps!
and btw the whole "marking each row with a special name" code is in usersTable.php
users.sql
create table users(
id int,
username varchar(50),
password varchar(50)
);
users.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "wdl2hw4db";
$conn = mysqli_connect($host, $username, $password, $database);
if (mysqli_connect_errno()){
die("can't connect to the Database" . mysqli_connect_errno());
}else{
echo "Database is connected" . "<br>";
}
if (isset($_POST['insert'])){
$idN1= $_POST['id'];
$usernameN1 = $_POST['username'];
$passwordN1 = $_POST['password'];
$query = "insert into users(id, username, pass) values ('".$idN1."' , '".$usernameN1."' , '".$passwordN1."' )";
$result = mysqli_query($conn, $query);
}else if (isset($_POST['update'])){
$idN2 = $_POST['id'];
$usernameN2 = $_POST['username'];
$passwordN2 = $_POST['password'];
$query = "update users set pass = '". $passwordN2 ."'where id = " . $idN2;
$result = mysqli_query($conn, $query);
}else if (isset($_POST['Display'])){
header('Location: usersTable.php');
}
echo "<br>";
?>
<form method="post">
ID: <input type="text" name="id" ><br><br>
username: <input type="text" name="username" ><br><br>
password: <input type="password" name="password" ><br><br>
<input type="submit" name="insert" value="insert">
<input type="submit" name="Display" value="Display">
</form>
userTable.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "wdl2hw4db";
$conn = mysqli_connect($host, $username, $password, $database);
$query = "select * from users";
$result = mysqli_query($conn, $query);
echo "<table border=\"6px\"><thead><tr><th>ID</th><th>username</th><th>password</th><th>Delete</th><th>Update</th></tr></thead>";
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><form method='post'><td>" . $row['id'] . "</td><td>" . $row['username'] . "</td><td>" . $row['pass'] . "</td><td><input type='submit' name='Delete" . $i . "' value='Delete'></td><td><input type='submit' name='Update" . $i . "' value='Update'><input type='text' name='UpdateText" . $i . "' placeholder='insert new password here'></td></form></tr>";
$i++;
}
echo "</table>";
$i = 1;
$result2 = mysqli_query($conn, $query);
while ($row2 = mysqli_fetch_assoc($result2)) {
if (isset($_POST['Delete' . $i])) {
$usernameN4 = $row2['username'];
$query2 = "delete from users where username ='" . $usernameN4 . "'";
$result2 = mysqli_query($conn, $query2);
header("Refresh:0");
break;
}
$i++;
};
$i = 1;
$result3 = mysqli_query($conn, $query);
while ($row3 = mysqli_fetch_assoc($result3)) {
if (isset($_POST['Update' . $i]) && $_POST['UpdateText' . $i] != null ) {
$id4 = $row3['id'];
$Utext = $_POST['UpdateText' . $i];
$query3 = "update users set pass ='" . $Utext . "' where id = " . $id4;
$result3 = mysqli_query($conn, $query3);
header("Refresh:0");
break;
}
$i++;
};
mysqli_free_result($result);
I have virtually no programming experience and trying this first project, I am a bit stuck on how to update the database, so I click on edit and the correct record gets loaded into the edit screen update.php
When I click update, I get the message from updated.php saying that the database has been updated, but the database does not get updated, when I display the records they are the same as before the update, thanks in advance for all your help.
the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Form Edit Data</title>
</head>
<body>
<table border=1>
<tr>
<td align=center>Form Edit Employees Data</td>
</tr>
<tr>
<td>
<table>
<?
$user_name = "";
$password = "";
$database = "";
$server = "localhost";
mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
$id = $_GET['id'];
$order = "SELECT * FROM MY_ID where ID = ' " .$id . " ' ";
$result = mysql_query($order);
$row = mysql_fetch_array($result);
?>
<form method="post" action="edit_data.php"?id=<?= $id ?>>
<input type="text" name="id" value="<? echo "$row[ID]"?>">
<tr>
<td>First Name</td>
<td>
<input type="text" name="FirsName" size="20" value="<? echo "$row[FirstName]"?>">
</td>
</tr>
<tr>
<td>Sur Name</td>
<td>
<input type="text" name="SurName" size="40" value="<? echo "$row[SurName]"?>">
</td>
</tr>
<tr>
<td>Address</td>
<td>
<input type="text" name="Address" size="40" value="<? echo "$row[Address]"?>">
</td>
</tr>
<tr>
<td align="right">
<input type="submit" name="submit" value="submit">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
and here is the other file
<?php
$user_name = "";
$password = "";
$database = "";
$server = "";
mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
$id = $_REQUEST['ID'];
$FirstName = trim(mysql_real_escape_string($_POST["FirstName"]));
$SurName = trim(mysql_real_escape_string($_POST["SurName"]));
$Address = trim(mysql_real_escape_string($_POST["Address"]));
$sql = "UPDATE MY_ID SET FirstName='$FirstName',SurName='$SurName',Address='$Address' WHERE ID='$id'";
$result=mysql_query($sql);
if ($result){
echo "Successful";
echo "<BR>";
echo "<a href='edit.php'>View result</a>";
}
else {
echo "ERROR";
}
?>
Looks like you forget the double quotation mark and the full stop. You should write it as: '".$example."'
$sql = "UPDATE MY_ID SET FirstName='".$FirstName."',SurName='".$SurName."',Address='".$Address.:' WHERE ID='".$id."'";
It is because your form method is POST, and you are trying to GET ID.
Probably ID returns null.
My suggestion is to put a hidden input in your form as with name="ID", then read it in your posted page as $_POST["ID"];
Yes, the answer is as Mansours said. You should not use single quota to your variable.
So, it's bad practice writing code something like this:
<input type="text" value="<?php echo "$row[name]"; ?>">
it should be
<input type="text" value="<?php echo $row['name']; ?>">
it would be clear, and also, when inserting or updating the record you should write as follow:
$sql = "UPDATE MY_ID SET FirstName='" . $FirstName . "',
SurName='" . $SurName . "',
Address='" . $Address . "'
WHERE ID='" . $id . "'";
mysql_query($sql);
i have an issue with my update function on php, i have the code to make the function work how ever it only ever updates the last function.
<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['update']))
{
$dbhost = '';
$dbuser = '';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$stock_1 = $_POST['stock_1'];
$stock_2 = $_POST['stock_2'];
$stock_3 = $_POST['stock_3'];
$stock_4 = $_POST['stock_4'];
$stock_5 = $_POST['stock_5'];
$stock_6 = $_POST['stock_6'];
$sql = "UPDATE products ".
"SET instock = $stock_1 ".
"WHERE productid = 1" ;
$sql = "UPDATE products ".
"SET instock = $stock_2 ".
"WHERE productid = 2" ;
$sql = "UPDATE products ".
"SET instock = $stock_3 ".
"WHERE productid = 3" ;
$sql = "UPDATE products ".
"SET instock = $stock_4 ".
"WHERE productid = 4" ;
$sql = "UPDATE products ".
"SET instock = $stock_5 ".
"WHERE productid = 5" ;
$sql = "UPDATE products ".
"SET instock = $stock_6 ".
"WHERE productid = 6" ;
mysql_select_db('db_k0903037');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">3.5" Seagate SATA 2TB</td>
<td><input name="stock_1" type="text" id="stock_1"></td>
</tr>
<tr>
<td width="100">Samsung 2.5" SATA Hard Drive</td>
<td><input name="stock_2" type="text" id="stock_2"></td>
</tr>
<tr>
<td width="100">8gb Kingston DDR3 RAM 1333mhz</td>
<td><input name="stock_3" type="text" id="stock_3"></td>
</tr>
<tr>
<td width="100">Apple MacBook Ram 8GB</td>
<td><input name="stock_4" type="text" id="stock_4"></td>
</tr>
<tr>
<td width="100">Gigabyte GA-970A-DS3</td>
<td><input name="stock_5" type="text" id="stock_5"></td>
</tr>
<tr>
<td width="100">Asus P8Z77-V PRO </td>
<td><input name="stock_6" type="text" id="stock_6"></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>
thats my code and im struggling to see why it doesnt update all of them? obviously i put in the correct username and password!
any help would be greatly appreciated.
Your mysql_select_db('db_k0903037'); must go at the top of the code, and then you have to do
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
after each $sql = "...";.
The way you do it, is you set the $sql string to something different each time, but you don't actually execute that query. mysql_query does the actual executing :)
Why don't you do that in a loop?
for($i=1;$i<=6;++$i){
${'stock_'.$i} = $_POST['stock_'.$i];
$sql = "UPDATE products SET instock = ".${'stock_'.$i}." WHERE productid = ".$i ;
$retval = mysql_query( $sql, $conn );
// ...
}
or just
for($i=1;$i<=6;++$i){
$var = $_POST['stock_'.$i];
$sql = "UPDATE products SET instock = ".$var." WHERE productid = ".$i ;
$retval = mysql_query( $sql, $conn );
// ...
}