I have an administrator.php which displays 300 records from a table called 'player'. Next to each record, there is an edit option which redirects you to edit.php and the 15 columns of that record (including the primary key - playerid) is displayed inside text boxes. Line of code below:
<a href='edit.php?playerid=".$query2['playerid']."'>Edit</a>
On edit.php you are able to change data of these columns. Upon submit, an update query is sent to update the table but unfortunately, it's not working. My error message continues to display ("testing for error..."); not sure why.
//Setups up the database connection
$link = mysql_connect("localhost", "root", "");
mysql_select_db("fantasymock", $link);
if(isset($_GET['playerid'])) {
$playerid = $_GET['playerid'];
//Query to display results in input box
$query1 = mysql_query("SELECT * from player WHERE playerid = '$playerid'");
$query2 = mysql_fetch_array($query1);
}
if(isset($_POST['submit'])) {
$playerid = $_POST['playerid'];
$preranking = $_POST['preranking'];
$playerlast = $_POST['playerlast'];
$playerfirst = $_POST['playerfirst'];
$position = $_POST['position'];
$battingavg = $_POST['battingavg'];
$run = $_POST['run'];
$homerun = $_POST['homerun'];
$rbi = $_POST['rbi'];
$sb = $_POST['sb'];
$win = $_POST['win'];
$save = $_POST['save'];
$strikeout = $_POST['strikeout'];
$era = $_POST['era'];
$whip = $_POST['whip'];
//Query to update dB
$query3 = mysql_query("UPDATE player SET playerid='$playerid', preranking='$preranking', playerlast='$playerlast', playerfirst='$playerfirst', position='$position', battingavg='$battingavg', run='$run', homerun='$homerun', rbi='$rbi', sb='$sb', win='$win', save='$save', strikeout='$strikeout', era='$era', whip='$whip' WHERE playerid='$playerid'");
header("Location: administrator.php");
} else {
echo "Testing For Error....";
}
?>
<form action="" method="POST">
Player ID:<input type="text" name="playerid" value="<?php echo $query2['playerid'];?>"/> <br/>
Preranking:<input type="text" name="preranking" value="<?php echo $query2['preranking'];?>"/> <br/>
Last Name:<input type="text" name="playerlast" value="<?php echo $query2['playerlast'];?>"/> <br/>
First Name:<input type="text" name="playerfirst" value="<?php echo $query2['playerfirst'];?>"/> <br/>
Position:<input type="text" name="position" value="<?php echo $query2['position'];?>"/> <br/>
Batting Avg:<input type="text" name="battingavg" value="<?php echo $query2['battingavg'];?>"/> <br/>
Runs:<input type="text" name="run" value="<?php echo $query2['run'];?>"/> <br/>
Homeruns:<input type="text" name="homerun" value="<?php echo $query2['homerun'];?>"/> <br/>
Rbi:<input type="text" name="rbi" value="<?php echo $query2['rbi'];?>"/> <br/>
Sb:<input type="text" name="sb" value="<?php echo $query2['sb'];?>"/> <br/>
Wins:<input type="text" name="win" value="<?php echo $query2['win'];?>"/> <br/>
Saves:<input type="text" name="save" value="<?php echo $query2['save'];?>"/> <br/>
Strikeouts:<input type="text" name="strikeout" value="<?php echo $query2['strikeout'];?>"/> <br/>
Era:<input type="text" name="era" value="<?php echo $query2['era'];?>"/> <br/>
Whip:<input type="text" name="whip" value="<?php echo $query2['whip'];?>"/> <br/>
<br>
<input type="submit" name="submit" value="submit">
</form>
FYI: Every column in the table and tablename is spelled correctly, I've triple checked before posting. And I'm aware of MySQL injection. Can someone see a problem? Thank you in advance!
EDIT: I just added an additional if statement if($query3) and it now works.
You are checking for POST variables, but you are getting to edit.php through a GET request. There isn't anything on $_POST. Therefore it drops down to the else of your if block and prints out Testing For Error...
Your script in getting into the else part. That means there nothing it is getting as $_POST['submit']. Make sure that your submit button must have a name attribute as submit.
<input type="submit" name="submit" value="" />
please check what showing in error.log file. You may insert these lines at your edit.php file
error_reporting(E_ALL);
ini_set('display_errors', 1);
to display error.
Replace your else part by this for more detailed mysql errors
else{ echo "Testing For Error...." .mysql_error(); }
Related
While editing a specific record using PHP code given below, all records in the database are edited simultaneously to the some garbage values. Here "db" is the Database. I am new to PHP and SQL. Please help
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date, $remarks, $isdate, $issuedto, $returndate)
{
?>
<!DOCTYPE HTML PUBLIC >
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<form action="edit.php" method="post">
<div>
<p><strong>Report No.:</strong> <?php echo $reportno; ?></p>
<strong>Date of receipt: *</strong> <input type="date" name="dateofreceipt" value="<?php echo $dateofreceipt; ?>"/><br/>
<strong>Report Title: *</strong> <input type="text" name="title" value="<?php echo $title; ?>"/><br/>
<strong>Report Type: *</strong> <input type="text" name="type" value="<?php echo $type; ?>"/><br/>
<strong>Issuing agency: *</strong> <input type="text" name="issuingagency" value="<?php echo $issuingagency; ?>"/><br/>
<strong>Marked to: *</strong> <input type="text" name="markedto" value="<?php echo $markedto; ?>"/><br/>
<strong>Date: *</strong> <input type="date" name="date" value="<?php echo $date; ?>"/><br/>
<strong>Remarks: *</strong> <input type="text" name="remarks" value="<?php echo $remarks; ?>"/><br/>
<strong>Issuing Date: *</strong> <input type="date" name="isdate" value="<?php echo $isdate; ?>"/><br/>
<strong>Issued To: *</strong> <input type="text" name="issuedto" value="<?php echo $issuedto; ?>"/><br/>
<strong>Return Date: *</strong> <input type="date" name="returndate" value="<?php echo $returndate; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$reportno = $_POST['reportno'];
$dateofreceipt = mysql_real_escape_string(htmlspecialchars($_POST['dateofreceipt']));
$title = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
$issuingagency = mysql_real_escape_string(htmlspecialchars($_POST['issuingagency']));
$markedto = mysql_real_escape_string(htmlspecialchars($_POST['markedto']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$remarks = mysql_real_escape_string(htmlspecialchars($_POST['remarks']));
$isdate = mysql_real_escape_string(htmlspecialchars($_POST['isdate']));
$issuedto = mysql_real_escape_string(htmlspecialchars($_POST['issuedto']));
$returndate = mysql_real_escape_string(htmlspecialchars($_POST['returndate']));
//renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date,$remarks, $isdate, $issuedto, $returndate, $error);
// save the data to the database
mysql_query("UPDATE `db` SET `Report No.`='[$reportno]',`Date of receipt`='[$dateofreceipt]',`Report Title`='[$title]',`Report Type`='[$type]',`Issuing agency`='[$issuingagency]',`Marked to`='[$markedto]',`Date`='[$date]',`Remarks`='[$remarks]',`Issuing date`='[$isdate]',`Issued to`='[$issuedto]',`Return Date`='[$returndate]' WHERE `Report No.`= '$id'")
// once saved, redirect back to the view page
header("Location: view.php");
}
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM db WHERE `Report No.`= '$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$reportno = $row['Report No.'];
$dateofreceipt = $row['Date of receipt'];
$title= $row['Report Title'];
$type= $row['Report Type'];
$issuingagency= $row['Issuing agency'];
$markedto= $row['Marked to'];
$date= $row['Date'];
$remarks=$row['Remarks'];
$isdate= $row['Issuing date'];
$issuedto= $row['Issued to'];
$returndate= $row['Return Date'];
// show form
renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date, $remarks ,$isdate, $issuedto, $returndate, '');
}
?>
Try this query for updation. Also dont forget to add semicolons after statements. Use mysqli_* Functions instead of mysql_*
mysqli_query("UPDATE `db` SET `Date of receipt`='$dateofreceipt',`Report Title`='$title',`Report Type`='$type',`Issuing agency`='$issuingagency',`Marked to`='$markedto',`Date`='$date',`Remarks`='$remarks',`Issuing date`='$isdate',`Issued to`='$issuedto',`Return Date`='$returndate' WHERE Report No = $reportno");
Several issues here:
The mysql api in PhP is deprecated. Don't bet on it working for longer. Use the mysqli api instead.
In your query the "where 1 part is completly superflous. 1 means true and where 1 means all records, at which point you can leave the WHERE out completly. You probably wanted to use WHERE somekey = 1, which is different.
try this
mysql_query("UPDATE db SET Report No.=".'$reportno'.",Date of receipt=."'$dateofreceipt'.",Report Title=."'$title'.",Report Type=."'$type'.",Issuing agency=."'$issuingagency'.",Marked to=."'$markedto'.",Date=."'$date'.",Remarks=."'$remarks'.",Issuing date=."'$isdate'.",Issued to=."'$issuedto'.",Return Date=."'$returndate'." WHERE Report No.= ."'$id'."")
Is it possible to update multiple records in one MySQLi query?
There are 4 records to be updated (1 for each element level) when the submit button is clicked.
The results are posted to a separate PHP page which runs the query and returns the user back to the edit page. elementid is 1,2,3,4 and corresponds with Earth, wind, fire, water. These never change (hence readonly or hidden)
<form id="edituser" name="edituser" method="post" action="applylevelchanges.php">
<fieldset>
<legend>Edit Element Level</legend>
<?php
while($userdetails->fetch())
{?>
<input name="clientid" id="clientid" type="text" size="8" value="<?php echo $clientid; ?>" hidden />
<input name="elementid" id="elementid" type="text" size="8" value="<?php echo $elementid;?>" hidden />
<input name="elemname" id="elemname" type="text" size="15" value="<?php echo $elemname; ?>" readonly />
<input name="elemlevel" id="elemlevel" type="text" size="8" required value="<?php echo $elemlevel; ?>" /></br>
</br>
<?php }?>
</fieldset>
<button type="submit">Edit Student Levels</button>
</form>
And the code to apply the changes
<?php
if (isset($_POST['clientid']) && isset($_POST['elementid']) && isset($_POST['elemname']) && isset($_POST['elemlevel'])) {
$db = createConnection();
$clientid = $_POST['clientid'];
$elementid = $_POST['elementid'];
$elemname = $_POST['elemname'];
$elemlevel = $_POST['elemlevel'];
$updatesql = "update stuelement set elemlevel=? where clientid=? and elementid=?";
$doupdate = $db->prepare($updatesql);
$doupdate->bind_param("iii", $elemlevel, $clientid, $elementid);
$doupdate->execute();
$doupdate->close();
$db->close();
header("location: edituserlevel.php");
exit;
} else {
echo "<p>Some parameters are missing, cannot update database</p>";
}
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" ...
I want to show the selected ID data in the form and EDIT it and UPDATE in the database. I selected the data from the database and put it in the input tag but it doesn't work. Please help!
<html>
<body>
<?
$db = mysql_connect("localhost", "root","");
mysql_select_db("db_ncs",$db);
$id = $_GET['s_id'];
if($id)
{
$result=mysql_query("SELECT * FROM tbl_student WHERE s_id=$id");
$row = mysql_fetch_assoc($result);
}
?>
<form method="post" action="update.php">
Name:<input type="Text" name="name" value="<?php echo $row['s_name'];?>" /><br>
Contact:<input type="Text" name="contact" value="<?php echo $row['s_contact'];?>" /><br>
Address:<input type="Text" name="address" value="<?php echo $row['s_address'];?>" /><br>
E-mail:<input type="Text" name="email" value="<?php echo $row['s_email'];?>" /><br>
<input type="submit" name="update" value="Update">
</form>
<?
if(isset($_POST['update']))
{
$name = $_POST['s_name'];
$contact = $_POST['s_contact'];
$address = $_POST['s_address'];
$email = $_POST['s_email'];
$sql = "UPDATE tbl_student
SET (s_name='$name', s_contact='$contact', s_address='$address', s_email='$email')
WHERE s_id=$id";
$res = mysql_query($sql);
if($res)
{
echo "Upadate Successfull!";
}
else
{
echo "Sorry!";
}
}
?>
</body>
</html>
You forgot to pass the id.
Add this between the <form> tags.
<input type="hidden" name="s_id" value="<?php echo $id;?>" />
You also need to make your methods consistent. The form submits the data via method="get" but you ask for it via $_POST. You also need to make the input names consistent with the names you ask for, by either adding or removing the "s_" in the appropriate places.
Not really an answer to your question, but i have to point you to some omissions in your code:
if $_POST['update'] is set, that doesn't mean the other variables are also set. They can be empty if user didn't enter anything in a field. You should check if every $_POST or $_GET variables are set by using isset or empty.
your code is so insecure! You should escape every variable before using it in a query. Use mysql_real_escape_string() for that. I also suggest you to use strip_tags() along with escaping.
In the form you have method="get" but you use $_POST in your PHP code. Try to define your form as below:
<form method="post" action="update.php">
Your SQL query should be (added quotes):
$sql = "UPDATE tbl_student
SET (s_name='$name', s_contact='$contact', s_address='$address', s_email='$email')
WHERE s_id=$id";
Try adding this after mysql_query:
$result = mysql_query($sql) or die(mysql_error());
Do not use mysql_* functions, they are no longer maintained: use PDO of MySQLi.
Doesn't he have to use the $row = mysql_fetch_assoc($result) to get the results?
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
http://php.net/manual/en/function.mysql-query.php
above is just an example.
update:
$result=mysql_query("SELECT * FROM tbl_student WHERE s_id=$id");
$row = mysql_fetch_assoc($result); // I think you have to add this line here, don't you?
?>
<form method="post" action="update.php">
<input type="hidden" name="s_id" value="<?php echo $id;?>" />
Name:<input type="Text" name="name" value="<?php echo $row['s_name'];?>" /><br>
Contact:<input type="Text" name="contact" value="<?php echo $row['s_contact'];?>" /><br>
Address:<input type="Text" name="address" value="<?php echo $row['s_address'];?>" /><br>
E-mail:<input type="Text" name="email" value="<?php echo $row['s_email'];?>" /><br>
<input type="submit" name="update" value="Update">
</form>
update 2:
when you are going to update, the method up there $id = $_GET['s_id']; is still looking for a param called 's_id' will come via HTTP GET, but it doesn't!
a quick workaround may be this,
<form method="post" action="update.php?<?php echo $id;?>">
and don't forget to add,
$id= $_POST['s_id']; after $email = $_POST['s_email'];!
update 3:
Hmm, You still need this <input type="hidden" name="s_id" value="<?php echo $id;?>" /> and don't forget to add,
$id= $_POST['s_id']; after $email = $_POST['s_email'];!
Your form has fields like name="contact", but when you try to get the values you use $_POST['s_contact']. These need to match.
The reason you need the hidden s_id field in the form is so that you will update the same row that was edited. Your UPDATE statement contains WHERE s_id=$id, so you need to get the original id this way. It's hidden because you don't want the user to be able to change the ID when editing.
I have looked everywhere here in Stackoverflow and I´ve searced 16.493 sites on Google but no answers to the most basic thing in php (edit record)
I´ve managed to code the most complicated stuff - but this is like a cancer and would also help others.
I have to files - edit.php - and update.php
edit.php works and it retrieves the data from the record
Here is the edit.php
<?php
mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$UID = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM cloudbig WHERE id = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$fs = $row['fs'];
$texti = $row['texti'];
}
?>
<form name="form1" method="post" action="update.php">
<input type="text" name="fs" value="<?php echo $texti ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
<?php
}
?>
and here is update.php
<?php
$id = $_REQUEST["id"];
$fs = $_POST["fs"];
$texti = $_POST["texti"];
mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
echo "MySQL Connection Established! <br>";
mysql_select_db("db") or die(mysql_error());
echo "Database Found! <br>";
$query = "UPDATE cloudbig SET fs = '$fs', texti = '$texti' WHERE id = '$id'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
I´ve done a whole news/online magazine site in php but simple edit.php function is a problem
I think that the short answer is that you never post the "id" up to the update.php script. Your form needs to look like this:
<form name="form1" method="post" action="update.php">
<input type="hidden" name="id" value="<?php echo $UID ?>">
<input type="text" name="fs" value="<?php echo $fs; ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
which will send the id into the POST array where it can be accessed by $id = $_REQUEST["id"];
You can also accomplish this by sending it via _GET by modifying the form action:
<form name="form1" method="post" action="update.php?id=<?php echo $UID ?>">
<input type="text" name="fs" value="<?php echo $fs; ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
which will put it in the $_GET array where it will also be seen in the $_REQUEST array.
Lastly, there are some MAJOR ISSUES with your code:
First and foremost, it is subject to SQL injection! You MUST escape
your variables before passing them into a MySQL query.
Second. As pointed out by iDifferent, you appear to bve echoing the wrong value into the fs field (you're setting it equal to the texti field)
Third, why do you have this loop?
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$fs = $row['fs'];
$texti = $row['texti'];
}
If you're fetching by ID you should never have duplicates. Make sure that ID is a primary key and there is no reason to check for multiple rows.