Updating Records
Workshop Requirements
Before beginning this workshop ensure that you have the ability to upload PHP files to a PHP enabled webserver that has a MySQL database server installed. See Setting Up a Server for details on how to install one if you don't already have access.
You should also have completed the following Virtual Workshops:
- PHP Web Databases - Part 1
- PHP Web Databases - Part 2
- PHP Web Databases - Part 3
- PHP Web Databases - Part 4
- The MySQL Series of Workshops
You should also have some experience with HTML programming.
A little bit of planning
So far we have been looking at the basic techniques of PHP and database integration without really worrying about where it is taking us. However in the last workshop we began to look at combining functions within the same script. To have a fully functioning database application we will need to add more functions (which wont be that hard) but at this stage we should identify them. We will need to be able to:
- Edit existing cd data
- Retrieve data ready to be edited
- Insert updated values into the database
- Add new cd data
- Display blank form fields for new data
- Insert new data into the database
- Add a new Copy
- Count Copies
- Add Copy
- Delete copy
- Get Available Copies
- Delete Copy
We will also need to connect to the database for each function/task , so rather than than repeating the code for making that connection in each function we will create a connection function that will assign the details to the $link variable which can be called from within the other variables. This will also allow us to add another little nicety which will make searching for an artist easier.
Reorganising the code
Before adding any more functions related to the different data manipulation tasks we should create the connection function and adjust the existing functions (html_form and select_artist) to use our new function.
First remove the connection code from the select_artist function and place that in out new function called my_conn. We also want to add a line 'return $link' as that will make that value available to whichever function uses (or calls) the connection function.
function my_conn() {
/* set's the variables for MySQL connection */
$server = "localhost:3306"; // this is the server address and port
$username = "vworksusr"; // change this to your username
$password = "vworkspass"; // change this to your password
/* Connects to the MySQL server */
$link = @mysql_connect ($server, $username, $password) or die (mysql_error());
/* Defines the Active Database for the Connection */
if (!@mysql_select_db("cdlibrary", $link)) {
echo "<p>There has been an error. This is the error message:</p>";
echo "<p><strong>" . mysql_error() . "</strong></p>";
echo "Please Contact Your Systems Administrator with the details";
}
return $link;
}
We next need to replace the code in the select_artist function with the single line that will call the function and assign the resulting connection reference (the returned $link variable) to a new variable called $conn.
function select_cd() {
?>
<h4>Cds Bought</h4>
<?
$conn = my_conn();
The value of $conn is the same as $link in our old example and so we also need to change the other references to $link within the select_artist function:
$result = mysql_query($sql, $conn);
...and...
mysql_close ($conn);
Save the file, upload it and check that everything still works. Assuming that we haven't broken everything it is time to add that nicety. The html_form function simply displays a blank form ready for user input. We could provide as an alternative a dropdown menu that will display all the available artists.
In order to achieve this will use our connection function, create a different SQL statement and use a while loop to create each option in a select form tag within our html_form function. Thus change the html_form function to read:
function html_form() {
/* Calls Connection Function */
$conn = my_conn();
/* Defines query */
$sql = "SELECT DISTINCT cd_releases.Artist FROM cd_releases;";
/* Passes query to database */
$result = mysql_query($sql, $conn);
if (!$result) {
echo("<p>Error performing query: " . mysql_error() . "</p>");
exit();
}
/* Outputs HTML form */
?>
<p>Please enter the search term for the artist</p>
<form name="cds" method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
Name of Artist: <select name="artist">
<?
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo("<option value=\"" . $row["Artist"] . "\">" . $row["Artist"] . "</option>\n");
}
?>
</select>
<input type="submit" name="Submit" value="ViewCds" />
</form>
<?
/* Closes Connection to the MySQL server */
mysql_close ($conn);
}
A few things to note about this code:
- The SQL statement is 'SELECT DISTINCT cd_releases.artist FROM cd_releases' which only selects each artist once.
- The retrieved value of artist is used twice - once as the form value and once as the display text within an HTML form select element.
We are now ready to start adding our new functions.
Editing existing data
As noted above updating a record will require two tasks - one to retrieve the record and place the values into a HTML form and another to process any changes made to data by the user. We will also need to add a couple of changes to the if control structure at the very beginning of our script that determines which function we want to use and also we need to add another column to our outputted 'artist' results in the function select_artist. This will allow the user to choose which record to edit.
Currently if the $_REQUEST['Submit'] array member exists, it doesn't matter what it's value is, the script performs a search for cds by the artist. We can change this so that if the array member exists AND its value determines the function to run. We know that the value of the first submit button is 'ViewCds' which means that we can adjust our code again to test for submit and the value 'ViewCds'.
if (!$_REQUEST['Submit']) {
html_form();
} elseif ($_REQUEST['Submit'] == "ViewCds") {
select_cd();
}
Note: A single equals-sign is used to assign a variable, to check for the matching variable we need to use a double equals-sign.
So let's add two functions to our if control statement. If 'Submit' has a value of 'Edit' this will trigger our get_data() function whereas if 'Submit' has a value of 'Update' this will update the database via the update_cd function.
if (!$_REQUEST['Submit']) {
html_form();
} elseif ($_REQUEST['Submit'] == "ViewCds") {
select_cd();
} elseif ($_REQUEST['Submit'] == "Edit") {
get_data();
} elseif ($_REQUEST['Submit'] == "Update") {
update_cd();
}
To add an additional column we will need to edit the select_artist artist function so that the output is similar to this with an edit link:
| Artist | Title | Year | Label | No of Tracks | |
| Christina Aguilera | Stripped | 2002 | RCA | 20 | Edit |
Thus make the following changes:-
Add a blank column in the first row of the table:
<td><strong>No of Tracks</strong></td>
<td></td>
</tr>
Next change the while control loop to read:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo("<tr>\n<td>" . $row["Artist"] . "</td>");
echo("<td>" . $row["Title"] . "</td>");
echo("<td>" . $row["Year"] . "</td>");
echo("<td>" . $row["Label"] . "</td>");
echo("<td>" . $row["No_of_tracks"] . "</td>");
echo("<td><a href=\"" . $_SERVER['PHP_SELF'] . "?releaseID=" .$row['releaseID'] . "&Submit=Edit\">Edit</a></td></tr>\n\n");
}
The new final column creates a URL link of 'cds.php?releaseid=number&Submit=Edit' this allows us to pass variables via the URL to the script as we saw in part 2. We are using the releaseID as an identifier because we don't need to know the copy number to edit the actual cd details. Also note that as there are double-quotes used in the echo string we need to 'escape' these (using a preceding backslash \") so that they are not included as part of the PHP code, but as outputted HTML. The final stage is to create a small get_data function so that we can test that everything is OK before going any further.
function get_data() {
echo "You wanna edit cd no. " . $_REQUEST['releaseID'];
}
Save the file, upload it and check that you get a message saying 'You wanna edit CD no. number' when you click edit next to a CD
Using the PRINT function
If we look at the echo function used to print out out edit column above you can see that it is becoming a bit complicated to join the variables and the outputted HTML, it is also a bit annoying to have to have an echo statement on every line. So from now on we are going to use the print function that allows us to include variables and normal text together AND print multiple lines.
Returning to our get_data() function we what to run an SQL query which retrieves the data based on the releaseID and then display that data in the form fields, with the option to update the record. The code that we are creating in this function is purely variations on what has gone before and so annotations throughout will offer explanations rather than re-explaining everything.
Note: With the print function the $row['name'] array members do not need the single quotes so put $row[name]:
function get_data() {
/* Calls our connection function */
$conn = my_conn();
/* Defines query */
$sql = "SELECT * FROM cd_releases WHERE (cd_releases.releaseID = " . $_REQUEST['releaseID'] . ")";
/* Passes query to database */
$result = mysql_query($sql, $conn);
if (!$result) {
echo("<p>Error performing query: " . mysql_error() . "</p>");
exit();
}
/* creates our row array with an if statement to report errors */
if ($row = @mysql_fetch_array($result, MYSQL_ASSOC)) {
/* prints out the artist and title */
print "<h4>$row[Artist] - $row[Title]</h4>";
/* prints out our HTML form '\"' */
print "<form name=\"CDs\" method=\"post\" action=\"$_SERVER[PHP_SELF]\">";
/* Prints out hidden releaseID - we don't put this in the HTML form
so that the uer cannot edit the Key value in error */
print "<input type=\"text\" name=\"releaseID\" value=\"$row[releaseID]\">";
/* prints out our HTML table and fields 'escaping' any double quotes '\"' */
print "<table width=\"600\">
<tr>
<td width=\"150\"><strong>Artist</strong></td>
<td width=\"350\"><input type=\"hidden\" name=\"artist\" value=\"$row[Artist]\"></td>
<td rowspan=\"5\" valign=\"top\"><input type=\"submit\" name=\"Submit\" value=\"Update\">
</td>
</tr>
<tr>
<td width=\"150\"><strong>Title</strong></td>
<td width=\"350\"><input type=\"text\" name=\"title\" value=\"$row[Title]\"></td>
</tr>
<tr>
<td width=\"150\"><strong>Year</strong></td>
<td width=\"350\"><input type=\"text\" name=\"year\" value=\"$row[Year]\"></td>
</tr>
<tr>
<td width=\"150\"><strong>Label</strong></td>
<td width=\"350\"><input type=\"text\" name=\"label\" value=\"$row[Label]\"></td>
</tr>
<tr>
<td width=\"150\"><strong>Tracks</strong></td>
<td width=\"350\"><input type=\"text\" name=\"tracks\" value=\"$row[No_of_tracks]\"></td>
</tr>
</table>
</form>";
} else {
echo("There has been an error" . mysql_error());
}
/* closes connection */
mysql_close ($conn);
}
Once more - save, upload and debug the script until you have it working.
Updating the Record
Now that the user has some fields to edit we need to add our update_cd function that will translate user changes to the field into changes in the database. To achieve this we will use an SQL update statement. We could do something complicated like retrieving the record then comparing each field to see if it has changed and if so update that field, but this is overkill. Following a chain of logic we are retrieving all the correct data from the database, thus inserting all the fields using just one statement (whether the user has modified the fields or not) will ensure that the correct data IS in the database.
Note: Once we process the query we simply call the get_data() function to display the updated values.
function update_cd() {
/* Calls our connection function */
$conn = my_conn();
/* Defines query */
$sql_update = "UPDATE cd_releases SET ";
$sql_update .= "cd_releases.Artist = '" . $_REQUEST['artist'] . "', ";
$sql_update .= "cd_releases.Title = '" . $_REQUEST['title'] . "', ";
$sql_update .= "cd_releases.Year = '" . $_REQUEST['year'] . "', ";
$sql_update .= "cd_releases.Label = '" . $_REQUEST['label'] . "', ";
$sql_update .= "cd_releases.No_of_tracks = '" . $_REQUEST['tracks'] . "' ";
$sql_update .= "WHERE (cd_releases.releaseID = " . $_REQUEST['releaseID'] . ")";
/* Passes query to database */
$result = mysql_query($sql_update, $conn);
if (!$result) {
echo("<p>Error performing query: " . mysql_error() . "</p>");
exit();
}
/* Prints succes message */
print "<p> Successfully Updated</p>";
/* closes connection */
mysql_close ($conn);
/* Calls get_data() function */
get_data();
}
That's the end of this workshop and if you are getting worried, don't. This has been the steep part of the learning curve part six (where we tidy up, adding new records, copies and deleting records) will be easier.
Full Code Listing
Rather than print it in this page you can get it here
Lastest 10 Threads - view all
Very good indeed, but!
Posted By: Mike Crawford at 10:26:07 on Monday the 11th of August 2003
I was expecting to be able to add new records to the DB. Is this easily added. It took me awhile to sort out the differing uppercase/lowercase files names to that of the database thus breaking the script so I would hate to break it again with me trying to add this 'New Record' functionality.
Regards Mike
So sorry
Posted By: Mike Crawford at 10:29:38 on Monday the 11th of August 2003
My apologies, please disregard my previous comment. I thought this tutorial was completed.
Regards Mike
Updating MySQL field thru PHP
Posted By: Mark at 10:08:23 on Tuesday the 12th of August 2003
i m creating a online quiz script using PHP n i want to auto update the marks of the students after they submit the quiz marks.. so how do i do the auto update. if u could help me soon then i would be thankful.
Re: Updating MySQL field thru PHP
Posted By: keith at 12:36:00 on Tuesday the 12th of August 2003
....you'd have to use a student ID to update their score to the current one. If you wanted to have a record or scores, you could add a score for each attempt and then manipulate the date during retrieval. I.e. show latest result and previous results in reverse cronological order......
explanation of code snipet \""
Posted By: Buddha Joe at 04:54:01 on Friday the 16th of January 2004
In this workshop there is something tht is nagging me for some reason In this code sample:
echo ("\n");
Manily the \"" and the "\" parts of the string. I do't understand what their significance. I understand that \n is for new line, the dots are for concatinating, but fail to grasp those two items.
I removed them just to see what would hapen and busted the script, but I expected that. can anyone explain this string a bt more?
correction
Posted By: Buddha Joe at 04:57:57 on Friday the 16th of January 2004
there is supposed to be a \ between the "" in the original post.
Never mind...
Posted By: Buddha Joe at 05:36:33 on Friday the 16th of January 2004
I get it now.. I had to break the string down into smaller pieces for me to see how the escpe sequence worked.
Keith.. You are awesome. I really appreciate you putting all o this together.
Sql query
Posted By: Radhika at 11:37:39 on Friday the 27th of February 2004
How can i store the count of updated records in SQL?
Re: Sql query
Posted By: keith at 11:45:17 on Friday the 27th of February 2004
...you want to store the number of updated records where?
Re: Re: Sql query
Posted By: Radhika at 11:56:33 on Friday the 27th of February 2004
I want to store the count of updated records as a variable or as a field in a table
Re: Sql query
Posted By: Keith at 12:03:09 on Friday the 27th of February 2004
use the mysql_affected_rows() function to assign the count to a variable.
Re: Re: Sql query
Posted By: Radhika at 11:59:18 on Friday the 27th of February 2004
I want to store the count of updated records as a variable or as a field in a table
PHP
Posted By: The Boy at 16:11:11 on Sunday the 27th of June 2004
Hi I am trying to write a databse for a fantasy football kind of thing. I am just starting out and have got the basics of MYSQL down to a tee however I wander if you can help me with this problem.
I know I need a page with all the players names and there scores. I can do that.
What I want to do is for the page where the user picks there team I want it so when ever I update the main scores table the scores would be updated in a seperate table for the players. I dont know what I have to do whether I need to use join or update I am at a loose end and I am getting headaches
Re: PHP
Posted By: keith at 16:16:55 on Sunday the 27th of June 2004
If you wanted to store the value then an update would be appropriate (working out the score in PHP) or you could generate each score 'on the fly' using a combination of joins and math functions.
Clear all and check all
Posted By: Saravanan at 09:53:14 on Tuesday the 7th of September 2004
how to delete the records using check box options clear all
while they all listed from a page
Re: Clear all and check all
Posted By: siri at 00:03:33 on Saturday the 22nd of January 2005
i would also liek to knwo how to edit a record when we have to check the checkbox
function problem
Posted By: Stuart at 10:42:25 on Tuesday the 7th of September 2004
Hi,
This tutorial has really helped me and I have been looking for something like this for months. This is quality work from you so thankyou.
Is it possible to send me the finished script as I am getting errors on the add_copy function. I dont like to give up but I have been trying to fix this for days now.
All the best stuart
Re: function problem
Posted By: stuart at 11:31:12 on Tuesday the 7th of September 2004
Sorry I meant this post to go onto the next page. (A Whole Application)
Re: function problem
Posted By: keith at 13:57:33 on Tuesday the 7th of September 2004
If you e-mail me the function I'll have a look, but I'm not sure I have a copy of the completed script around anymore.
Parse error
Posted By: mike at 16:49:24 on Wednesday the 8th of September 2004
keep getting error on line 106:
"echo("<a href="" . $_SERVER['PHP_SELF'] . "?releaseID=" .$row['releaseID'] . "&Submit=Edit">Edit</a>nn");"
Seems to be fine but won't run for some reason
Thank you for your good tutorials!
Mike
Re: Parse error
Posted By: keith at 16:54:28 on Wednesday the 8th of September 2004
you've missed the blackslash from before the final quote within the variable
Parse error
Posted By: Mike at 16:52:51 on Wednesday the 8th of September 2004
I've put slashes before "" but its not shown them here.
Mike
Php
Posted By: Arpana at 10:53:15 on Thursday the 21st of October 2004
the value of my hidden field is an image and I'm unable to retrieve that image and display it! plz help!
Error with updating
Posted By: Kristy at 01:17:10 on Monday the 3rd of January 2005
This is a great tutorial! Just what I was looking for. However, I keep getting the error: Error performing query: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE (id = '')' at line 1.
This is my code, which appears correct and I don't understand why I keep getting this error: $sql_update .= "WHERE (runtotals.id = '" . $_REQUEST['id'] . "')"; The table name is runtotals and the primary key is id Thanks in advance for your help.
Re: Error with updating
Posted By: keith at 01:20:13 on Monday the 3rd of January 2005
....for whatever reason the ID is not being included in the statement (the missing value '') try printing the intended value back to your browser first to debug the problem.
update format
Posted By: Chris at 23:19:23 on Tuesday the 22nd of March 2005
I will explain the problem: I can add a record to my data base using a form page that I made in PHP. I can add records as long as they don't contain " or ' in the fields to be added. If I try to edit the information it is either truncated or missing altogether. I think it is a easy problem to fix if I could find the missing answer. How can I make PHP look at the entire data in a field as one peice of html and not PHP code?
Re: update format
Posted By: keith at 00:10:17 on Wednesday the 23rd of March 2005
...sue the addslashes() function
http://uk.php.net/manual/en/function.addslashes.php
Test
Posted By: Sonam at 05:25:03 on Monday the 9th of October 2006
This is a test and hope this works out fine
Delete multiple records using multiple c
Posted By: Ruwanthi Perera at 08:48:47 on Friday the 29th of April 2005
i don't know how to delete multiple records using multiple check boxes. i use PHP and the database is mySQL
Syntax Error After Insterting update_cd
Posted By: Steve at 13:09:58 on Saturday the 18th of June 2005
You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
I've tried everything and I can't seem to figure out why the UPDATE function is screwing it up.
Re: Syntax Error After Insterting update
Posted By: Steve at 02:39:19 on Friday the 24th of June 2005
I figured out the error problem but now i am having difficulties with when I click the update button the database does not get updated. What may have I forgotten or what did I take out that I wasnt supposed too?
Error in updating!?
Posted By: Subramanian at 12:16:26 on Friday the 1st of July 2005
Hi Keith! I have gone through your tutorials.I want to know what is wrong with the following code of mine to update the record in a form that I have created.Once I run this program, Id is asked and when I give my ID,That particular record is displayed in the form.Strange,The previous data in all other fields are present but only the value in EMAIL field is set to size=20.When I enter a new value, even the old value escapes from the field giving the field an empty value.Can u help me out?
$ud_Email=$_POST['Email']; mysql_query("UPDATE work SET Email=='$ud_Email' WHERE ref='$anju'");
Updating Multiple Tables
Posted By: John at 15:25:53 on Saturday the 23rd of July 2005
Keith, Let me first say great stuff here. However, I cant seem to get an update across multiple tables to work? Is there a specific mysql syntax that is suppose to be used based on the version of mysql that is being used. Any type of code sample woudl be a helpful hint. Thanks and keep up the good work.
John
Re: Updating Multiple Tables
Posted By: keith at 16:15:07 on Saturday the 23rd of July 2005
....yup. An update join (as it is called) see part 5 of the mysql series or workshops....
one fielf using multiple textboxes
Posted By: bhaskar at 11:12:54 on Thursday the 28th of July 2005
suppose enter name: feild is there.that feilld having 5 textboxes.suppose we enter the data in (Ex:2 r 3 )textboxes that data only stored in database.how to writ code in php. iam using sql database.
one field using multiple textboxes
Posted By: bhaskar at 11:13:08 on Thursday the 28th of July 2005
suppose enter name: feild is there.that feilld having 5 textboxes.suppose we enter the data in (Ex:2 r 3 )textboxes that data only stored in database.how to writ code in php. iam using sql database.
file updation
Posted By: haneefa at 06:23:19 on Thursday the 26th of April 2007
how can i update multiple rows having uploaded files in the field
can you help me?
Posted By: zcherie Ann at 07:46:17 on Thursday the 10th of May 2007
I just want to ask if you could help me in my problem about php.
I need a codes wherein the user can update or delete records that was already saved in the mysql.. I need your urgent answer.. thank you and god bless
Just look at me & talk ))
Posted By: Nnatawaat at 11:20:36 on Sunday the 22nd of July 2007
My nickname is Natahot1229 ....why don't you join now , that I can talk to you...online members page!!! http://searchresultspage.tripod.com
& Maybe yes---maybe no...
Posted By: Chicasensu at 18:08:43 on Monday the 6th of August 2007
Maybe sex- I don't know....My nick is ChicaSensual20...wanna see me on cam?...chat page!!! http://talktomehere.tripod.com
Alexios
Posted By: Alexios at 09:31:06 on Thursday the 6th of September 2007
Your site has very much liked me. I shall necessarily tell about him to the friends. family fued [url=http://family-fued.odday.info] family fued [/url] downloadable family feud family feud history family feud richard dawson activation code family feud download family feud free full version family fued family feud game brown family feud james family feud [url=http://family-fued.odday.info/family-feud-theme.html] family feud theme [/url][url=http://family-fued.odday.info/free-family-feud--.html] free family feud [/url][url=http://family-fued.odday.info/family-feud-game-show--.html] family feud game show [/url][url=http://family-fued.odday.info/family-feud-free-full-version.html] family feud free full version [/url][url=http://family-fued.odday.info/family-feud-2.html] family feud 2 [/url][url=http://family-fued.odday.info/family-feud-iwin.html] family feud iwin [/url]
Goodiok
Posted By: hiutopor at 20:49:23 on Monday the 17th of September 2007
Hi
Very interesting information! Thanks!
G'night
& Now explore your naughty side
Posted By: Aalbertafe at 20:10:34 on Wednesday the 3rd of October 2007
Maybe yes-maybe no, maybe sex- I don't know....My nick is ChicaSensual20...wanna see me on cam?...chat page!!! http://chicachat.tripod.com
Продаю сертификаты Вебмани.
Posted By: neownefroxy at 13:34:07 on Friday the 5th of October 2007
Привет. Продаю персональный сертификат WebMoney за $99. Можете проверить: WMID 322973398779 Redfern Всё чисто, не одной жалоб. Сделан на утерянные документы. Всё законно. Если нужно, то есть сертификаты ещё. Стучацо в личную почту на Вебмани.
Это не спам. Не пишите на мой WMID жалобы в арбитраж Вебмани.

non-destructive update?
Posted By: Bill at 11:58:58 on Sunday the 29th of June 2003
I've been searching all over the net for the answer, and I've come up empty. What statement would I use if I wanted to update a field without losing the existing data? In other words, I want to add data to the field, not replace it. Any/all help would be most appreciated! :)
Reply to this comment
Re: non-destructive update?
Posted By: keith at 13:24:25 on Sunday the 29th of June 2003
If you look at part 9 of the mysql series (Built in functions) there is a section called 'String Functions' that includes information about how to add values to a field.
Reply to this comment
Re: Re: non-destructive update?
Posted By: Bill at 15:47:21 on Sunday the 29th of June 2003
YOWZA! Thanks man...finally I have a clear answer! You're the best. Thanks for your time & effort on these tutorials and helping folks get the job done!
Reply to this comment