Page 1 of 1

Checking a Table

Posted: Sat Mar 29, 2003 10:21 am
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?

Posted: Sat Mar 29, 2003 10:44 pm
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.

Posted: Sun Mar 30, 2003 5:42 pm
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?!

Posted: Mon Mar 31, 2003 8:47 am
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; 
   }

Posted: Mon Mar 31, 2003 9:40 am
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