PHP database not updating, no errors - php

I have a page of entries with an edit button behind each entry, clicking it brings you to the edit page of that entry, the form has the existing data of that entry as default values. I change the values and click update, it redirects where it should, no errors but also no change in the data entry values.
My form:
<form method="post" action="edit.php" enctype="multipart/form-data">
Item name:</br>
<input type="text" name="item_name" value="<?php echo $row[1]; ?>"></br></br>
<input type="hidden" name="item_id" value="<?php echo $row[0]; ?>">
Item price:</br>
<input type="text" name="item_price" value="<?php echo $row[3]; ?>" ></br></br>
Item image:</br>
<input type="file" name="item_image"value="<?php echo $row[4]; ?>" ></br></br>
Item description:</br>
<textarea type="text" class="txtinput" cols="55" rows="20" name="item_description"><?php echo $row[2]; ?>"</textarea></br></br>
<input type="submit" name="submit" value="Uppdate entry">
</form>
My PHP:
<?php
include("includes/connect.php");
if( isset($_GET['edit']))
{
$id= $_GET['edit'];
$res= mysql_query("SELECT * FROM shop_items WHERE item_id=$id");
$row= mysql_fetch_array($res);
}
if( isset($_POST['submit']))
{
$item_name = $_POST['item_name'];
$id = $_POST['item_id'];
$item_price = $_POST['item_price'];
$item_image = $_FILES['item_image'];
$image_tmp = $_FILES['item_image'] ['tmp_name'];
$item_description = $_POST['item_description'];
if ($item_name=='' or $item_price=='' or $item_image=='' or $item_description==''){
echo "<script>alert('One or more of your fields are blank, please ensure you have entered content in ALL fields.')</script>";
}
else {
move_uploaded_file($image_tmp,"images/$item_image");
$sql = "UPDATE shop_item SET item_name='$item_name', item_price='$item_price,' item_image='$item_description', item_name='$item_description' WHERE item_id='$id'";
echo "<meta http-equiv='refresh' content='0;url=admin_shop.php'>";
}
}
?>

You're not actually running your SQL query to update the database! You've stored the SQL query in a variable, $sql, but you haven't actually called mysql_query($sql);
} else {
move_uploaded_file($image_tmp,"images/$item_image");
$sql = "UPDATE shop_item SET item_name='$item_name', item_price='$item_price,' item_image='$item_description', item_name='$item_description' WHERE item_id='$id'";
// Add this line
mysql_query($sql);
echo "<meta http-equiv='refresh' content='0;url=admin_shop.php'>";
}
However, MySQL functionality is deprecated. You should look into PDO: http://uk3.php.net/pdo or mysqli: http://uk3.php.net/mysqli

Change this -
$sql = "UPDATE shop_item SET
item_name='".mysql_real_escape_string($item_name)."',
item_price='".mysql_real_escape_string($item_price)."',
item_image='".mysql_real_escape_string($item_description)."',
item_name='".mysql_real_escape_string($item_description)."'
WHERE item_id='$id'";
$exe = mysql_query($sql) or die(mysql_error());
NOTE: Avoid using mysql_* function since they are deprecated and use mysql_* or PDO instead.

Related

Undefined variable row even on accessing it with index values [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
I am getting the data from db and updating it here and trying to sending back to db. The error is undefined variable row.I am accessing with index values instead of their names.
<!DOCTYPE HTML>
<?php
include_once('DBConnection.php');
if( isset($_GET['edit']) )
{
$id = $_GET['edit'];
$res= mysql_query("SELECT * FROM details WHERE id='$id'");
$row= mysql_fetch_array($res);
}
if( !empty($_POST['newName'])&& isset($_POST['newName'])&& !empty($_POST['email'])&& isset($_POST['email'])&&!empty($_POST['phonenumber'])&& isset($_POST['phonenumber']))
{
$newName = $_POST['newName'];
$EMail = $_POST['email'];
$PhoneNumber = $_POST['phonenumber'];
$id = $_POST['id'];
$sql = "UPDATE details SET name='$newName' email='$EMail' phonenumber='$PhoneNumber' WHERE id='$id'";
$res = mysql_query($sql)
or die("Could not update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=random.php'>";
}
?>
<form action="edit.php" method="POST">
PhoneNumber: <input type="text" name="phonenumber" value="<?php echo $row[3];?>"/><br />
EMail: <input type="text" name="email" value="<?php echo $row[2];?>"/><br />
Name: <input type="text" name="newName" value="<?php echo $row[1];?>"/><br />
SlNo<input type="hidden" name="SlNo" value="<?php echo $row[0];?>"/>
<input type="submit" value=" Update "/>
</form>
In this instance, you need to be sure $row is defined before using it. Try this:
<!DOCTYPE HTML>
<?php
include_once('DBConnection.php');
if( isset($_GET['edit']) )
{
$id = $_GET['edit'];
$res= mysql_query("SELECT * FROM details WHERE id='$id'");
$row= mysql_fetch_array($res);
}
if( !empty($_POST['newName'])&& isset($_POST['newName'])&& !empty($_POST['email'])&& isset($_POST['email'])&&!empty($_POST['phonenumber'])&& isset($_POST['phonenumber']))
{
$newName = $_POST['newName'];
$EMail = $_POST['email'];
$PhoneNumber = $_POST['phonenumber'];
$id = $_POST['id'];
$sql = "UPDATE details SET name='$newName' email='$EMail' phonenumber='$PhoneNumber' WHERE id='$id'";
$res = mysql_query($sql)
or die("Could not update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=random.php'>";
}
?>
<form action="edit.php" method="POST">
PhoneNumber: <input type="text" name="phonenumber" value="<?php echo (isset($row)? $row[3]: "");?>"/><br />
EMail: <input type="text" name="email" value="<?php echo (isset($row)? $row[2]: "");?>"/><br />
Name: <input type="text" name="newName" value="<?php echo (isset($row)? $row[1]: "");?>"/><br />
SlNo<input type="hidden" name="SlNo" value="<?php echo (isset($row)? $row[0]: "");?>"/>
<input type="submit" value=" Update "/>
</form>
You haven't done a SELECT query and executed it in your second if. There is no $row variable defined, yet you talk about it in your form.
The query() method shall return FALSE on fail, which is a boolean, which has no rows...
Before trying to access the result rows, check if it is an array :
$res = mysql_query($sql);
if (!is_array($res)) {
return ('error');
}
$row = mysql_fetch_array($res);
and also make sure $row exists, as Elisha said.
Also to concatenate strings and variables : PHP - concatenate or directly insert variables in string (Note that you method perhaps works, I don't know)

PHP - Undefined index : id - the value is not retrieved

Yes, I know there is a lot of 'Undefined index' questions floating around here and i have been looking through them before asking this question. I copied the codes from those questions to try and test it out but it still doesn't work for my own project. Also, I'm still a beginner in PHP.
So here is my problem. I wanted to try coding a simple edit form after I have finished coding the delete and view form.
This is my code
<?php
require("config.php");
$id = $_GET['id'];
echo "id: ".$id;
$sql = "SELECT * FROM contracts WHERE id= '$id'";
$result = $con->query($sql);
$row = $result->fetch_assoc()
?>
<form action="editform.php" method="GET">
ID:
<?php echo $id; ?><br>
Contract Title<br>
<input type="text" name="contract_title" value="<?php echo $row['contract_title']; ?>" /><br>
<input type="submit" name = "edit "value="Update" />
</form>
?php
if(isset($_POST['edit']) ){
$id = $_GET['id'];
$upd= "UPDATE `contracts` SET
`contract_title`='".$_POST['contract_title']."',
WHERE `id`='".$_POST['id']."";
if($do_upd = $con->query($upd))
{
echo "Update Success";
}
else
{
echo "Update Fail";
}
}
?>
This is the before the error.
This is the error I received.
In line 3, the id is not retrieved after I clicked the button update.
It didn't retrieved the values.
What mistakes did I do in the coding and how do I fix it? Thanks in advance.
Right below:
<form action="editform.php" method="GET">
Add:
<input type="hidden" name="id" value="<?php echo $id; ?>" />
Update:
Fixed other errors in your code:
<?php
require("config.php");
$id = $_GET['id'];
echo "id: ".$id;
$sql = "SELECT * FROM contracts WHERE id= '$id'";
$result = $con->query($sql);
$row = $result->fetch_assoc()
?>
<form action="editform.php" method="GET">
ID: <?php echo $id; ?><br>
Contract Title<br>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="contract_title" value="<?php echo $row['contract_title']; ?>" /><br>
<input type="submit" name="edit" value="Update" />
</form>
<?php
if(isset($_GET['edit']) ){
// needs escaping!~~~
$upd= "UPDATE `contracts` SET `contract_title` = '".$_GET['contract_title']."' WHERE `id` = '".$id;
if($do_upd = $con->query($upd)) {
echo "Update Success";
} else {
echo "Update Fail";
}
}
Please consider escaping your database input to prevent SQL injection
<?php
require("config.php");
$id = $_GET['id'];
echo "id: ".$id;
$sql = "SELECT * FROM contracts WHERE id= '$id'";
$result = $con->query($sql);
$row = $result->fetch_assoc()
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$contract_title = $row['contract_title'];
}
} else {
echo "0 results";
}
if(isset($_POST['edit']) ){
$upd = "UPDATE contracts SET contract_title='$contract_title' WHERE id='$id'";
if($do_upd = $con->query($upd))
{
echo "Update Success";
}
else
{
echo "Update Fail";
}
}
?>
<form action="" method="POST">
ID:
<?php echo $id; ?><br>
Contract Title<br>
<input type="text" name="contract_title" value="<?php echo $row['contract_title']; ?>" /><br>
<input type="submit" name = "edit" value="Update" />
</form>

how to get the last inserted id and how to check in where condition to update query using php

Hi iam inserting the data into database table and redirecting to another page and need to insert the details into the same table by comparing ids and email.But how to get the last inserted id and compare in where condition to update the details.
Here is my code:
index.php
<form method="post" action="properties.php" id="myform">
<input type='hidden' value="<?php echo $username; ?>" name='email'>
<tr><th>Interest Paid</th><td><input type="text" name="house_interest_paid" value=""/></td>
<tr><th>Total Interest Paid</th><input type="text" name="house_total_interest_paid" value=""/></td>
<tr><th>House Number</th><input type="text" name="house_number" value=""/></td>
<tr><th>Street</th><input type="text" name="house_street" value=""/></td>
<button type="submit" class = "large awesome yellows" onClick="document.location.href='ownerproperty.php'"> Specify Co-owners Property</button> </span>
</form>
properties.php
$email=$_POST['email'];
$interest=$_POST['house_interest_paid'];
$interestpaid=$_POST['house_total_interest_paid'];
$number=$_POST['house_number'];
$street=$_POST['house_street'];
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
if($query)
{
session_start();
header("Location:ownerproperty.php");
}
else{
echo "Registration has not been completed.Please try again";
}
ownerproperty.php
<form style="display:none" method="POST" action="owner.php">
<h2>Owner Property details</h2>
<input type='hidden' value="<?php echo $username; ?>" name='email'>
<?php include "ownership.php"; ?>
<p><label for="name_coowner">Coowner Name</label> <input value="<?php echo $row['name_coowner'];?>" type="text" name="name_coowner" /></p>
<p><label for="pan_coowner">PAN Of Coowner</label> <input value="<?php echo $row['pan_coowner'];?>" type="text" name="pan_coowner" /></p>
<button type="submit" class = "medium" style="background-color: #2daebf;">Save</button>
</form>
Ownership.php
$res = "SELECT * FROM house_details
WHERE email ='$username'";
$result=mysql_query($res);
$row = mysql_fetch_array($result);
Owner.php
$email=$_POST['email'];
$owner_name=$_POST['name_coowner'];
$pan_owner=$_POST['pan_coowner'];
$query=mysql_query("UPDATE house_details SET name_coowner='$owner_name',pan_coowner='$pan_owner'
WHERE email='$email' AND house_details_id='2'");
if($query)
{
session_start();
header("Location:rentalproperty.php");
}
For the first time when i click on submit button the data is inserting into db and redirecting to ownerproperty.php .in that i need to get the inserted id and need to comapre that id and email and need to update the owner property details in the same column when the email and id are same.But how to get that id and compare in the where condition can anyone help me.
properties.php
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
$id = mysql_insert_id(); //For last inserted id.
if($query)
{
session_start();
$_SESSION['sess_id'] = $id; // Set one session variable for last inserted id.
header("Location:ownerproperty.php");
}
owner.php
<?php
session_start(); // Start your session
$id = $_SESSION['sess_id']; // Use this id in query
$email=$_POST['email'];
$owner_name=$_POST['name_coowner'];
$pan_owner=$_POST['pan_coowner'];
$query=mysql_query("UPDATE house_details SET name_coowner='$owner_name',pan_coowner='$pan_owner'
WHERE email='$email' AND house_details_id='2'");
if($query)
{
session_start();
header("Location:rentalproperty.php");
}
[NOTE : mysql extensions are deprecated. Use PDO or mysqli_ database extensions.]
You can add this:
$stmt = 'SELECT LAST_INSERT_ID() as sessionId';
Which should grab the ID from the last insert.
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
if($query)
{
//Last inserted ID
$last_id = $query->insert_id;
session_start();
header("Location:ownerproperty.php");
}
else{
echo "Registration has not been completed.Please try again";
}
You can add this:
$stmt = 'SELECT MAX(house_details_id) AS "id" FROM house_details';
$result=mysql_query($stmt);
$row = mysql_fetch_array($result);
$id = $row['id'];

Weird error when updating database using php

I have a weird problem in which if I delete the line Type doctor name <input type="text" name="new_Doctor_name" value="<?php echo $row1[3]; ?>" ><br />, I cannot update my records and get the notice Undefined variable: row1. However, if I keep this line, which I copy from another table, I can update just fine.
Please explain this. Any help will be highly appreciated.
<?php
include_once('Connect.php');
if( isset($_GET['edit1']) )
{
$id = $_GET['edit1'];
$res1= mysql_query("SELECT * FROM department WHERE Dept_name='$id'");
$row1= mysql_fetch_array($res1);
}
if( isset($_POST['new_Doctor_name']) )
{
$id = $_POST['id'];
$new_Dept_name = $_POST['new_Dept_name'];
$new_Ward = $_POST['new_Ward'];
$sql1 = "UPDATE department SET Dept_name='$new_Dept_name', Ward='$new_Ward' WHERE Dept_id='$id'";
$res2 = mysql_query($sql1) or die("Could not Update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=Department_viewtable.php'>";
}
var_dump($row1);
?>
<FORM ACTION="Department_dmod.php" METHOD="post">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
***Type doctor name <input type="text" name="new_Doctor_name" value="<?php echo $row1[3]; ?>" ><br />***
Type Department Name <input type="text" name="new_Dept_name" value="<?php echo $row1[1]; ?>" ><br />
Type Department Ward <input type="text" name="new_Ward" value="<?php echo $row1[2]; ?>" >
<INPUT TYPE="SUBMIT" NAME="UPDATE" VALUE="UPDATE">
<p><a href=Department_viewtable.php>Back to the Department table</a></p>
<p><a href=Main_Menu.php>Back to Main menu</a></p>
</FORM>
The if() statement :
if( isset($_POST['new_Doctor_name']) )
Will only ever be executed if an input element exists in the POST data with a name of new_Doctor_name. If you remove it from the DOM, it will not be passed with the request, and thus the queries won't execute.
It may be better to check for the presence of the UPDATE variable inside the POST request:
if(isset($_POST['UPDATE']))
{
$id = $_POST['id'];
$new_Dept_name = $_POST['new_Dept_name'];
$new_Ward = $_POST['new_Ward'];
$sql1 = "UPDATE department SET Dept_name='$new_Dept_name', Ward='$new_Ward' WHERE Dept_id='$id'";
$res2 = mysql_query($sql1) or die("Could not Update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=Department_viewtable.php'>";
}
It's also worth noting that the mysql_* family of functions is now deprecated. Instead, you should look at MySQLi or PDO. Finally, your code is open to SQL injection, so I'd recommend looking at Prepared Statements, too.
The variable row1 is set in this part of the code. If the variable is returning an error that it has not been defined this means that the code below has not been executed. This code is only ran if the $_GET['edit1'] variable is set.
if( isset($_GET['edit1']) )
{
$id = $_GET['edit1'];
$res1= mysql_query("SELECT * FROM department WHERE Dept_name='$id'");
$row1= mysql_fetch_array($res1);
}

updating a record in database not working

again I'm trying to study php mysql and it seems that I tried everything thing to figure the problem out.. but it seems as a beginner codes in the internet are not helping.. I really can't update the records in the database.
<html>
<body>
<?php
$db = mysql_connect("localhost", "root");
mysql_select_db("dbtry",$db);
$id = isset($_GET['id']) ? $_GET['id'] : null;
$submit = isset($_POST['submit']);
if ($id) {
if ($submit) {
$result = mysql_query("select * from employees where id = " . mysql_real_escape_string($_GET['id']) );
$row = mysql_num_rows($result);
if ($myrow != 0) {
mysql_query ("UPDATE employees SET firstname='$first',lastname='$last',address='$address',position='$position' WHERE id = '$id'");
}
echo "Thank you! Information updated.\n";
} else {
// query the DB
$result = mysql_query("SELECT * FROM `employees` WHERE `id` = " . mysql_real_escape_string($_GET['id']), $db);
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">
First name:<input type="Text" name="first" value="<?php echo $myrow["firstname"] ?>"><br>
Last name:<input type="Text" name="last" value="<?php echo $myrow["lastname"] ?>"><br>
Address:<input type="Text" name="address" value="<?php echo $myrow["address"]
?>"><br>
Position:<input type="Text" name="position" value="<?php echo $myrow["position"]
?>"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
}
} else {
// display list of employees
$result = mysql_query("SELECT * FROM employees",$db);
while ($myrow = mysql_fetch_array($result)) {
printf("%s %s<br>\n", $_SERVER['PHP_SELF'], $myrow["id"],
$myrow["firstname"], $myrow["lastname"]);
}
}
?>
</body>
</html>
There are two things potentially causing you a problem: firstly, the values you are trying to set are variables which have not been defined. I'm assuming the begginers code you found assumed you had register globals enabled, you really don't want to do this!
The second problem, is that if you do have register globals enabled, the data isn't being sanitized, so a quotation mark could send the update awry.
Try this instead:
$first = mysql_real_escape_string( $_POST['first'] );
$last = mysql_real_escape_string( $_POST['last'] );
$address= mysql_real_escape_string( $_POST['address'] );
$position = mysql_real_escape_string( $_POST['position'] );
mysql_query ("UPDATE employees SET firstname='$first',lastname='$last',address='$address',position='$position' WHERE id = '$id'");
This should at least get you up and running. I'd strongly advise that you use either the MySQLi library, or PHP PDO, and think about using prepared statements for added security.
mysql_query("UPDATE `employees` SET `firstname`='".$first."', `lastname`='".$last."',
`address`='".$address."', `position`='".$position."' WHERE `id` = '".$id".' ; ", $db) or
die(mysql_error());
I think the problem may lie in your connection to the database. The third parameter of the mysql_connect function is a password. Therefore this:
$db = mysql_connect("localhost", "root");
should be:
$db = mysql_connect("localhost", "root", "yourPassword");
It would also help a lot if you posted what type of error you are getting.
You need to differentiate post and get. Follow the working example below. It will sort you out :D
<html>
<body>
<?php
$db = mysql_connect("localhost", "root","");
mysql_select_db("test",$db);
if($_SERVER['REQUEST_METHOD']=='POST')
{
//SUBMIT FORM
$id=isset($_POST['id'])?$_POST['id']:0;
if ($id) {
$result = mysql_query("select * from parameter where id = " . mysql_real_escape_string($id) );
$rows = mysql_num_rows($result);
if ($rows != 0) {
mysql_query ("UPDATE parameter SET name='".$_POST['name']."',value='".$_POST['value']."' WHERE id = '".$id."'");
echo "Thank you! Information updated.\n";
}
}
}
if($_SERVER['REQUEST_METHOD']=='GET')
{
//SELECT WHERE ID=GER VAR AND DISPLAY
$id = isset($_GET['id']) ? $_GET['id'] :0;//
if ($id) {
// query the DB
$result = mysql_query("SELECT * FROM parameter WHERE `id` = " . mysql_real_escape_string($_GET['id']), $db);
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">
First name:<input type="Text" name="name" value="<?php echo $myrow["name"] ?>"><br>
Last name:<input type="Text" name="value" value="<?php echo $myrow["value"] ?>"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
}
else {
// display list of employees
$result = mysql_query("SELECT * FROM parameter",$db);
while ($myrow = mysql_fetch_array($result)) {
echo "<a href='".$_SERVER['PHP_SELF']."?id=".$myrow['id']."'>".$myrow['name'].": ".$myrow['value']."</a><br>";
}
}
}
?>
</body>
</html>
Usually when I run into this problem, it's because auto commit is off and I forgot to tell the connection explicitly to commit.
EDIT: Have you tried this: How can I implement commit/rollback for MySQL in PHP?? Depending on your settings, InnoDB can be set to auto commit off, which means you need to tell MySQL explicitly to commit updates after your done.

Categories