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

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)

Related

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>

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

PHP database not updating, no errors

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.

Unable to edit mysql row using form

I am trying to create a form that will edit rows from my db table. (Based on some code I got from a StackOverflow page.)
I am able to populate the form with relevant data, but when I submit the form, the row isn't updated. In fact, some of my columns are deleted.
What did I do wrong?
edit.php
<?php
$UID = (int)$_GET['f'];
$query = mysql_query("SELECT * FROM user_feeds WHERE feed_id = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$feedtitle = $row['feed_title'];
$feedurl = $row['feed_url'];
$feedorder = $row['feed_order'];
$feedowner = $row['feed_owner'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$UID;?>">
Title:<br /> <input type="text" name="ud_feedtitle" value="<?=$feedtitle?>"><br>
URL: <br /> <input type="text" name="ud_feedurl" value="<?=$feedurl?>"><br>
Order: <br /> <input type="text" name="ud_feedorder" value="<?=$feedorder?>"><br>
Owner:<br /> <input type="text" name="ud_feedowner" value="<?=$feedowner;?>"><br>
<input type="Submit">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</div>
</body>
</html>
update.php
<?php
$ud_ID = $_REQUEST["ID"];
$ud_feedtitle = $_POST["feed_title"];
$ud_feedurl = $_POST["feed_url"];
$ud_feedorder = $_POST["feed_order"];
$ud_feedowner = $_POST["feed_owner"];
$query = "UPDATE user_feeds SET feed_title = '$ud_feedtitle', feed_url = '$ud_feedurl', feed_order = '$ud_feedorder', feed_owner = '$ud_feedowner', WHERE feed_id = '$ud_ID'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
Reason:
The name of the input field is the same name by which $_POST is populated. The variables you are currently requesting :
$_POST["feed_title"];, $_POST["feed_url"];, $_POST["feed_order"];, $_POST["feed_owner"];
are all empty as they don't exist. When updating, you are replacing the values in your table with blank values.
Solution:
In your update.php, the following should be there instead.
$ud_ID = $_POST["ID"];
$ud_feedtitle = $_POST["ud_feedtitle"]; //corresponding to <input type="text" name="ud_feedtitle" ...
$ud_feedurl = $_POST["ud_feedurl"]; //corresponding to <input type="text" name="ud_feedurl" ...
$ud_feedorder = $_POST["ud_feedorder"]; //corresponding to <input type="text" name="ud_feedorder" ...
$ud_feedowner = $_POST["ud_feedowner"]; //corresponding to <input type="text" name="ud_feedowner" ...

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