Jump to content

[SOLVED] Ensure a variable passed through through URL exists?


FridayRain

Recommended Posts

It just donned on me that I need an error message if someone tries to go to a page with a variable in the URL that doesn't correspond to a database entry.

 

For example, http://www.domain.com/poetry.php?piece=4 does not yet exist. Say I only have three poems in the database right now. What are some ways (or the best way) to make sure the variable leads to content or to otherwise display an error message?

Simple.. if your new poetry entries are assigned a unique identifier upon submission, then if someone queues a poetry.php?poem=4, and there is not a poem assigned to that identifier (It should return nothing, or a blank array) then, you simply print out "Poem does not exist"

Each piece has an id, so it returns nothing, but I have formatting around where the text would go, so it looks tacky. If no piece is selected, basically an isset function, then a message is displayed regarding selecting a piece. But if someone tries an id number that doesn't exist, how is PHP to know to display another message, like Piece does not exist?

Are you returning the poems from the database? If so, then something along the lines of:

<?php

$query = "SELECT poem FROM table WHERE piece = {$_GET['piece']}";

$result = mysql_query($query);

if(mysql_num_rows($result) == 0){
   echo "The poem you selected does not exitst.";
}

else{
   $poem = mysql_fetch_assoc($result);
   echo $poem['body'];
}

?>

 

should work.

 

EDIT: Keep in mind that you'll need to use the name of your script variables and database table columns and not exactly what I wrote above. I just guessed when naming the variables and columns in the example above.

Thanks. I tried my own IF statement and it seems to be working.

 

<?php
    if($content[title] == "")
        {
        echo "<p>Poem does not exist. Please choose a title.</p>";
        }
    else { // blah blah }
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.