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?

Link to comment
Share on other sites

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"

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.