This question already has an answer here:
I'm building up that simple html form for inserting/retrieving data to/from mysql database. Just started up with two buttons: find and reset. Both of them are working fine BUT when I click FIND while fields are empty these errors coming up:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in V:\u\miramo\Forum\xampp\htdocs\miramo_licensedb\myclass.php on line 76
Warning: mysql_free_result() expects parameter 1 to be resource, boolean given in V:\u\miramo\Forum\xampp\htdocs\miramo_licensedb\myclass.php on line 81
This is myclass.php
piece:
public function find() {
$this->queryString = $this->makeQueryString();
$this->errorMessages=$this->queryString;
$query = mysql_query ($this->queryString);
while($row=mysql_fetch_array($query)):
$this->id= $row['id'];
$this->name= $row['name'];
$this->email = $row['email'];
endwhile;
mysql_free_result($query);
and myform.php:
<?php
include_once("./myclass.php");
$my_class = new MyClass;
?>
<form action="myform.php" method="post">
<input type="text" value="<?php echo $my_class->id; ?>" name="id" class="" />
<input type="text" value="<?php echo $my_class->name; ?>" name="name" class="" />
<input type="text" value="<?php echo $my_class->email; ?>" name="email" class="" />
<input type="submit" name="find" value="Find" />
<input type="submit" name="reset" value="reset" />
</form>
I tried to sort that out by adding
if($result === FALSE){
die(mysql_error());
}
before my while loop but it didn't help. Was hoping that in case of running query on empty fields message "Insert values" will come up. Any suggestions??? Help highly appreciated
And thats the query:
public function makeQueryString(){
// build array of search terms
$res= "SELECT id, name, email FROM test1 ";
// build array of search terms
$i=0;
if ($_POST['id'])
$searchTermsArray[$i++] = "id LIKE '{$_POST['id']}'";
if ($_POST['name'])
$searchTermsArray[$i++] = "name LIKE '{$_POST['name']}'";
if ($_POST['email'])
$searchTermsArray[$i++] = "email LIKE '{$_POST['email']}'";
// Construct query string from search terms array
if ($i > 0 ) {
$j=0;
$res .= " WHERE " . $searchTermsArray[0];
for ($j=1; $j < $i; $j++)
$res = $res . " AND " . $searchTermsArray[$j];
}
else
$res= "";
//Return query string
return($res);
}
</div>
The problem is that you're attempting to execute an empty query. Check for this case before executing your generated query (which may be empty);
public function find() {
$this->queryString = $this->makeQueryString();
if(empty($this->queryString))
{
echo "Insert values";
return;
}
else
{
$this->errorMessages=$this->queryString;
$query = mysql_query ($this->queryString);
while($row=mysql_fetch_array($query)):
$this->id= $row['id'];
$this->name= $row['name'];
$this->email = $row['email'];
endwhile;
mysql_free_result($query);
}