PHP & MYSQL TUTORIAL/PROGRESS BLOG
Comments/Guest Book
PAGE 3 "Creating and Retrieving MySQL Data"
This adds the values to their relative fields, so ordering the fields and values correctly is essential. Do not add the ID as one of the fields, as the ID field is handled automatically.Comments/Guest Book
PAGE 3 "Creating and Retrieving MySQL Data"
Adding data to the database
To add the data you must use a query. Add the following code to your php file, after "mysql_select_db($dbname);" and before "?>"
$query = "INSERT INTO example1 (Name, Subject, Comment, URL) VALUES ('Bob', 'Hey', 'Once upon a time, the end', 'http://chrisgibbo.blogspot.com')";
mysql_query($query) or die('Error, insert query failed');
Save the file (as a .php file) and open it in your browser. There will still be nothing there (if there is an error go back through and make sure you didn't miss anything. Now go into the phpMyAdmin front end. Go into the table under the database you created and choose browse. You should see the information there. Try refreshing the php file you created several times to ensure that it keeps adding the data on to the end.
Retrieving data from the database
The following will only display data which already exists in the database. It will not add it and then display it, so ensure you have followed the above section first before trying this bit.
The final code to both enter the data and retrieve it:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error
connecting to mysql');
$dbname = 'test1';
mysql_select_db($dbname);
$query = "INSERT INTO example1 (Name, Subject, Comment, URL) VALUES ('a', 'b', 'c', 'd')";
mysql_query($query) or die('Error, insert query failed');
$query = "SELECT Name, Subject, Comment, URL FROM example1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo " Name :{$row['Name']} <br>" .
"Subject : {$row['Subject']} <br>" .
"Comment : {$row['Comment']} <br>" .
"URL: {$row['URL']} <br>.<br>";
}
?>
Save and refresh to show the same page with the added content (a, b, c and d in my example). Keep refreshing and the page should add the same data to the bottom of the page over and over again.
Information/help from:
Collin Jensen
php.net
php mysql tutorial
©Chris Guiblin 2008
URL: www.guiblin.com/chris/
EMAIL: chris@guiblin.com
No comments:
Post a Comment