Checking a Table

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
bobthebobert
Forum Commoner
Posts: 25
Joined: Sat Feb 15, 2003 5:56 pm

Checking a Table

Post by bobthebobert »

What I want to do is to be able to check a table to see if it already has the number I want to assign to someone else. This is what I have so far:

Code: Select all

<?php
$randd=rand(1,10);
while ($coord <> $randd) {
	$randd=rand(1,10);
	$used = mysql_query("SELECT coords FROM miscel WHERE (coords = '$randd')");
	while ($row = mysql_fetch_array($used)) {
		$used = ("$row[0]");
	}
	if ($randd <> $used) {
		$coord = $randd;
	} 
}
?>
This works, but whenever it finds that $randd has already been used in the table, it displays an error. It changes the number, but it still displays the error =/. How can I get it to not display an error?
nincha
Forum Contributor
Posts: 191
Joined: Fri Mar 28, 2003 12:30 pm
Location: CA, USA

Post by nincha »

could the error be the syntax error from "$coord <> $randd" because i dont think $coord can be both less than $randd and greater than it at the same time.
bobthebobert
Forum Commoner
Posts: 25
Joined: Sat Feb 15, 2003 5:56 pm

Post by bobthebobert »

I am pretty sure <> is the same as saying does not equal.

Anyone have any ideas why it gives me an error sometimes?!
Rob the R
Forum Contributor
Posts: 128
Joined: Wed Nov 06, 2002 2:25 pm
Location: Houston

Post by Rob the R »

It looks to me that the problem is because you redefine the $used variable. If you find a match, the $used variable get the row results, but then the next time through the while loop (since for all it knows, there may be other matches it has to fetch) it tries to issue a "mysql_fetch_array($used)" command, but $used no longer stores the query text.

Try either removing the while loop just so you do one fetch:

Code: Select all

$used = mysql_query("SELECT coords FROM miscel WHERE (coords = '$randd')"); 
   $row = mysql_fetch_array($used) ;
   if ($row !== false) {
      $used = ("$row[0]"); 
   }
or using a variable other than $used to store the results:

Code: Select all

$used_value = 0 ;
   while ($row = mysql_fetch_array($used)) { 
      $used_value = ("$row[0]"); 
   } 
   if ($randd <> $used_value) { 
      $coord = $randd; 
   }
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

On a side note, you don't need the parenthesis and quotes in this statement:

Code: Select all

$used = ("$row[0]");
you could just do:

Code: Select all

$used = $row[0];
Mac
Post Reply