March 23, 2009

How can I use PHP to generate a URL, each time a new entry is made into a MySQL database?

mysql
Kizzeith asked:


I want to be able to enter info into a MySql db via a php form (I know how to do that.) When it’s entered, I want to have a URL generated automatically that the record (entered) can be viewed from…

Does that make sense? Does PHP have a function for this?

Filed under Programming & Design by administrator

Permalink Print

Comments on How can I use PHP to generate a URL, each time a new entry is made into a MySQL database?

March 26, 2009

Mohamed.Mansour @ 1:12 pm

Hello,

It is called, ‘viewing contents from your database from PHP’.

First thing you have to do is know the difference between URL Requests. If you want a URL to be something similar to that will get the ITEM #1 from the database. We are supplying parameters to the URL ( ?id=1 ) which will form a GET Request Method.

To tell PHP to process that message, in your items.php file, you could do the following:
—————-
if( isset( $_GET['id'] ) { // Check if ID parameter exists
$id = $_GET['id'];
echo ‘ID => ‘,$id;
}
—————-

What I just showed, it will print to the screen ID => 1, since I did the following . So by using that code, you can query the database for the content you need to be displayed:
—————-
// Create some connection to the database ..
$conn = ….
…..

// Check GET Input
if( isset( $_GET['id'] ) { // Check if ID parameter exists
$id = $_GET['id'];
$query = sprintf(’SELECT name,desc FROM items WHERE id=%d’, intval($id));
$result = mysql_query($query);

// Fetch the row
$row = mysql_fetch_object($result);
echo ‘Name: ‘, $row->name,’ ‘;
echo ‘Desc: ‘, $row->desc,’ ‘;

}
else
{
echo ‘Invalid Request => Nothing in GET request’;
}
—————-

Basically, that is the way you will use a URL to access Database.. Make sure you look into properly protecting your database from MySQL injections, I used sprintf to format the query since that will help me force named parameters for security injections. You should use MySQL REAL ESCAPE in php for more formatting,

That is it,
1) you use GET request method for grabbing URI parameters
2) you use that parameter and you could filter it (input handling if needed)
3) you use that parameter to query the database using WHERE clause to query one item from DB (that you inserted) usually you query by index
4) you print them out

You can print all contents in the database if your database result set contains more than one item, you can use a while loop.

Good Luck