Jump to content

Empty Variable


Manny
 Share

Recommended Posts

I am redesigning my site and changing code from HTML to PHP SQL using a database to retrieve news articles.Now, this is a link that would work because the number of the variable is located in the database. (/news/?id=158)However, when the variable is left empty (ie. (/news/?id=) ) or a number is entered that isn't in the database, the user gets a blank screen.What do I need to enter that would redirect them to my 404 page.

Link to comment
Share on other sites

I suppose you're using a query.Perform the query:$id = intval($_GET['id']);$query = mysql_query("SELECT * FROM table WHERE id={$id}");And then if nothing is found (number of rows in the query equal to 0), you redirect them, but do it before any content is written to the page because you're sending headers:if(!mysql_num_rows($query)) {header("Location: otherpage.html");}

Link to comment
Share on other sites

Here is a cut-down version of my code to show what I've done.

<? $id = $_GET["id"];?> <? $dbserverIP="localhost";$dbusername="USERNAME";$dbuserpassword="PASSWORD";$connection = mysql_connect($dbserverIP,$dbusername,$dbuserpassword) or die("Couldn't connect to the dbserver."); $dbname="DATABASE";$dbselectok = mysql_select_db($dbname,$connection) or die("Couldn't select database.");$sqlstatement = "SELECT * FROM `TABLE` WHERE `ID` = '$id'";$sql_result = mysql_query($sqlstatement,$connection) or die("<BR /><BR /><span class=\"c3\">Page could not be displayed.</span>");while ($row = mysql_fetch_array($sql_result)){VARIABLESprint "CONTENT";}?>
I tried what you said but it seems as though I've done it differently. The code above works when the variable is valid, but when it isn't a white screen appears.
Link to comment
Share on other sites

You're missing the intval() call, which is the key thing here. Regardless of what you put in intval(), it will return an integer - thus, it's valid in the query.I'd personally also check if the variable is empty though, as otherwise, you may see an unidentified index warning.

$id = empty($_GET['id']) ? intval($_GET['id']) : 0);

In addition, you're also missing the condition. Put it before the while loop.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...