I am working on a page that I need to be able to update single records from my MySQL database using PHP. Can someone please help me? When I try to update one record all my other records are updated.
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>Name: *</strong> <input class="form-control" type="text" name="name" value="<?php echo $name; ?>" /><br/>
<strong>Month: *</strong> <input class="form-control" type="text" name="month" value="<?php echo $month; ?>" /><br/>
<strong>event1: *</strong> <input class="form-control" type="text" name="event1" value="<?php echo $event1; ?>" /><br/>
<strong>event2: </strong> <input class="form-control" type="text" name="event2" value="<?php echo $event2; ?>" /><br/>
<strong>event3: </strong> <input class="form-control" type="text" name="event3" value="<?php echo $event3; ?>" /><br/>
<strong>event4: </strong> <input class="form-control" type="text" name="event4" value="<?php echo $event4; ?>" /><br/>
<strong>timesub: </strong> <input class="form-control" type="text" name="timesub" value="<?php echo $timesub; ?>" readonly /><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit" class="btn btn-info">
<input type=reset name="reset" value="Reset" class="btn btn-danger">
</div>
</form>
That is my form, and then I follow it with this code:
<?php
}
include('db_connect.php');
if (isset($_POST['submit'])) {
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$month = mysql_real_escape_string(htmlspecialchars($_POST['month']));
$event1 = mysql_real_escape_string(htmlspecialchars($_POST['event1']));
$event2 = mysql_real_escape_string(htmlspecialchars($_POST['event2']));
$event3 = mysql_real_escape_string(htmlspecialchars($_POST['event3']));
$event4 = mysql_real_escape_string(htmlspecialchars($_POST['event4']));
$timesub = mysql_real_escape_string(htmlspecialchars($_POST['timesub']));
// check thatfields are filled in
if ($name == '' || $month == '' || $event1 == '' || $timesub == ''){
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $month, $event1, $event2, $event3, $event4, $timesub, $error);
} else {
// save the data to the database
mysql_query("UPDATE announcement SET name='$name', month='$month', event1='$event1', event2='$event2', event3='$event3', event4='$event4', timesub='$timesub'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
} else
// if the form hasn't been submitted, get the data from the db and display the form
{// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM announcement WHERE id=$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
$name = $row['name'];
$month = $row['month'];
$event1 = $row['event1'];
$event2 = $row['event2'];
$event3 = $row['event3'];
$event4 = $row['event4'];
$timesub = $row['timesub'];
// show form
renderForm($id, $name, $month, $event1, $event2, $event3, $event4, $timesub, '');
} else {// if no match, display result
echo "No results!";
}
} else {// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
echo 'Error!';
}
}
?>
I got the code from: http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
Great article!
Thanks in advance for the help.
First of all stop using mysql_* its deprecated and closed in PHP 7. You can use mysqli_* or PDO.
Whats wrong with your query:
This is very important, if you not use WHERE CLAUSE in your UPDATE STATEMENT than it will update the all rows.
You must need to add WHERE CLAUSE in your query at end, something like:
WHERE id = '$id'
Also note that, your code is open for SQL INJECTION, you must need to prevent with SQL INJECTION, you can learn about the prepared statement. This post will help you to understand: How can I prevent SQL injection in PHP?
*If you want to know How mysqli_* works, this document will help you: http://php.net/manual/en/book.mysqli.php
If you want to work on PDO, you can follow this manual: http://php.net/manual/en/book.pdo.php
Take a close look at your query:
mysql_query("UPDATE announcement SET name='$name', month='$month', event1='$event1', event2='$event2', event3='$event3', event4='$event4', timesub='$timesub'")
Your query is missing a WHERE clause. Without a WHERE clause, your query will update all rows in the table announcement. You need to add something like:
WHERE id='$id'
This will restrict the update to only the row you want to update.
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'."")
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'];
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(); }
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 am working on a project. What I need to do is basically enter some info into a form, have that form save it into a database, display the data, and then be able to edit the data. So far, I am able to do everything except edit the data. I've tried using $_GET to get the ID of the particular "bug" I need to edit, and I am able to do that, and get all of the information but I am not sure how to edit that particular ID in my database. Here is my handler: http://pastebin.com/mR6QWpJ7 and my form:
<form action="week10handle.php" method="POST">
<fieldset width="300px">
<legend width="300px"><b>Add a bug report</b></legend>
Product Name:<br/><input type="text" name="product_name"><br/>
Product Version: <br/><input type="text" name="product_version"><br/>
Hardware Type: <br/><input type="text" name="hardware"><br/>
Operating System: <br/><input type="text" name="os"><br/>
Frequency: <br/><input type="text" name="frequency"><br/>
Proposed Solutions: <br/><textarea name="solutions"></textarea><br/>
<input type="submit" value="Submit">
</fieldset>
</form>
Here is where I obtain the get data in my edit form page so far, but as of right now, I am not sure how to edit a particular ID in the database.
$getbug = htmlspecialchars($_GET["bugid"]);
if (!empty($getbug)){
$getbuginfo = mysql_query("SELECT * FROM `bugs` WHERE `id`= '$getbug'");
if ($getbuginfo = mysql_fetch_assoc($getbuginfo)){
$edit_product_name = $getbuginfo['product_name'];
$edit_prod_version = $getbuginfo['product_version'];
$edit_hardware = $getbuginfo['hardware_type'];
$edit_os = $getbuginfo['os'];
$edit_frequency = $getbuginfo['frequency'];
$edit_solutions = $getbuginfo['solutions'];
?>
<form action="week10handle.php" method="POST">
<fieldset width="300px">
<legend width="300px"><b>Edit bug <?php echo $getbug;?></b></legend>
Product Name:<br/><input type="edit" name="product_name" value="<?php echo $edit_product_name;?>"><br/>
Product Version: <br/><input type="edit" name="product_version" value="<?php echo $edit_prod_version;?>"><br/>
Hardware Type: <br/><input type="edit" name="hardware" value="<?php echo $edit_hardware;?>"><br/>
Operating System: <br/><input type="edit" name="os"value="<?php echo $edit_os;?>"><br/>
Frequency: <br/><input type="edit" name="frequency"value="<?php echo $edit_frequency;?>"><br/>
Proposed Solutions: <br/><textarea name="solutions"><?php echo $edit_product_name;?></textarea><br/>
<input type="submit" value="Submit">
</fieldset>
</form>
EDIT: Here is my update php code, but it is still not working, when I submit my form, it refreshes the page, but it doesn't update the database:
<?php
if (mysql_connect('localhost','root','') && mysql_select_db('bug_reports')){
$errors = array();
if (isset($_POST['product_name'], $_POST['product_version'],$_POST['hardware'],$_POST['os'],$_POST['frequency'], $_POST['solutions'])){
$product_name = mysql_real_escape_string(htmlentities($_POST['product_name']));
$product_version = mysql_real_escape_string(htmlentities($_POST['product_version']));
$hardware = mysql_real_escape_string(htmlentities($_POST['hardware']));
$os = mysql_real_escape_string(htmlentities($_POST['os']));
$frequency = mysql_real_escape_string(htmlentities($_POST['frequency']));
$solutions = mysql_real_escape_string(htmlentities($_POST['solutions']));
$getbug = mysql_real_escape_string(htmlentities($_POST['bugid']));
if (empty($product_name) || empty($product_version) || empty($hardware) || empty($os) || empty($frequency) || empty($solutions)){
$errors[] = 'All fields are required.';
}
if (!is_numeric($product_version) || !is_numeric($frequency)){
$errors[] = 'Product version and frequency must both be numbers';
}
if (empty($errors)){
$update = "UPDATE `bugs` SET `product_name` = '$product_name', `product_version = '$product_version', `hardware_type = '$hardware', `os` = '$os', `frequency` = '$frequency', `solutions` = '$solutions' WHERE `id` = $getbug";
if ($update = mysql_query($update)){
header('Location: week10handle.php');
} else{
$errors[] = 'Something went wrong, please try again.';
}
} else{
foreach($errors as $error){
echo '<p><strong>'.$error.'</strong></p>';
}
}
}else{
$getbug = htmlspecialchars($_GET["bugid"]);
}
if (!empty($getbug)){
$getbuginfo = mysql_query("SELECT * FROM `bugs` WHERE `id`= '$getbug'");
if ($getbuginfo = mysql_fetch_assoc($getbuginfo)){
$bugid = $getbuginfo['id'];
$edit_product_name = $getbuginfo['product_name'];
$edit_prod_version = $getbuginfo['product_version'];
$edit_hardware = $getbuginfo['hardware_type'];
$edit_os = $getbuginfo['os'];
$edit_frequency = $getbuginfo['frequency'];
$edit_solutions = $getbuginfo['solutions'];
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<fieldset width="300px">
<legend width="300px"><b>Edit bug <?php echo $getbug;?></b></legend>
Product Name:<br/><input type="edit" name="product_name" value="<?php echo $edit_product_name;?>"><br/>
Product Version: <br/><input type="edit" name="product_version" value="<?php echo $edit_prod_version;?>"><br/>
Hardware Type: <br/><input type="edit" name="hardware" value="<?php echo $edit_hardware;?>"><br/>
Operating System: <br/><input type="edit" name="os"value="<?php echo $edit_os;?>"><br/>
Frequency: <br/><input type="edit" name="frequency"value="<?php echo $edit_frequency;?>"><br/>
Proposed Solutions: <br/><textarea name="solutions"><?php echo $edit_product_name;?></textarea><br/>
<input type="hidden" name="bugid" value="<?php echo $bugid;?>" >
<input type="submit" value="Update">
</fieldset>
</form>
<?
}else{
echo "something went wrong";
}
}else{
echo "No bug found.";
}
}else
echo 'Could not connect at this time.';
?>
A typical way to detect an update, as opposed to an insert, would be to check for a value for id. So, in your edit form add a hidden field to pass the id to the handler and then in your handler you can decide whether to process it as insert or update based on the presence of the id field.
if (isset($_GET['id']) {
// do update
$sql = 'UPDATE `bugs` SET ... WHERE id = ' . intval($_GET['id']);
} else {
// do insert
$sql = 'INSERT INTO `bugs` VALUES ....';
}
UPDATE `bugs` SET `product_name` = '...', `product_version` = '...', ... WHERE `id` = $bugid;
Where the "..." will be replaced with newly $_POST-ed values for each column