phpurl

How to get ID from GET?


I'm building my first website that pulls info from a MySQL table. So far, I've successfully managed to connect to the database and get the information I need.

My website is set up to display a single record from the table, which it is doing. However, I need some way of changing the URL for each record, so I can link pages to specific records. I have seen on websites like Facebook that everyone's profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552

I'd like to base my ID on the primary key on my table, for example, location_id.

I've included my php code so far,

<?php
require "connect.php";
$query =  "select * from location limit 1";
$result = @mysql_query($query, $connection) 
or die ("Unable to perform query<br>$query");
?>

<?php
while($row= mysql_fetch_array($result))
{
?>

<?php echo $row['image'] ?>

<?php
}
?>

Thanks


Solution

  • Use $_GET to retrieve things from the script's query (aka command line, in a way):

    <?php
    
    $id = (intval)$_GET['id'];  // force this query parameter to be treated as an integer
    
    $query = "SELECT * FROM location WHERE id={$id};";
    $result = mysql_query($query) or die(mysql_error());
    
    if (mysql_num_rows($result) == 0) {
       echo 'nothing found';
    } else {
       $row = mysql_fetch_assoc($result);
       echo $row['image'];
    }