Page 1 of 1

checking if a field exists in a database

Posted: Tue Sep 02, 2008 3:05 pm
by keisx
Hi! Right now I'm trying to write somehow a small piece of code that should show me the text from the DB that I want. I'll try to explain it more detailed:

so I have a link, for example, http://www.mypage.com/index.php?id=green and when I click on it, I receive my id, which I needed. The problem is - I can't imagine how is it possible to check if my 'id' is valid, by which I mean that the section exists in the database (DB), because obviously someone could type http://www.mypage.com/index.php?id=mynameisjohn manually and receive a blank page, however it would be nice to tell them something like "The page that you're viewing, doesn't exist".
I added my code, however it's a simple code, I would rather say that it's just a connection to my DB.

Code: Select all

<? 
if(isset($_GET['id'])) $id = $_GET['id']; else $id = 'info'; \\ this only works, if the id is empty
 
// this is where the actions should be
 
$konekcija=mysql_connect('127.0.0.1','*','*') or die ("Unable to connect");
mysql_select_db('*',$konekcija);
$vaicajums2="select * from `text` where section='$id' and `lang`='lv'";
$rezultats=mysql_query($vaicajums2,$konekcija);
$rezultats2=mysql_fetch_array($rezultats);
 
echo "$rezultats2[1]";
 
mysql_close($konekcija);
?>
 

Re: checking if a field exists in a database

Posted: Tue Sep 02, 2008 3:22 pm
by andyhoneycutt
You can check to make sure there are any results in the first place before showing them, e.g.:

Code: Select all

...
$rezultats=mysql_query($vaicajums2,$konekcija);
// Add here:
if( is_resource($rezultats) )
{
  $rezultats2=mysql_fetch_array($rezultats);
  echo "$rezultats2[1]";
}
mysql_close($konekcija);
?>
 

Re: checking if a field exists in a database

Posted: Tue Sep 02, 2008 3:46 pm
by keisx
seems to be a good idea (didn't know about this function), but somehow it doesn't want to work - it just shows me a blank screen every time I enter an invalid id.

Re: checking if a field exists in a database

Posted: Thu Sep 04, 2008 2:54 pm
by andyhoneycutt
I would suggest your query isn't returning any data then.

Re: checking if a field exists in a database

Posted: Thu Sep 04, 2008 8:11 pm
by paperplate
keisx wrote:seems to be a good idea (didn't know about this function), but somehow it doesn't want to work - it just shows me a blank screen every time I enter an invalid id.
add an "else" clause after line 8 to echo/print out an error message.