我正在构建这个简单的html表单,用于向/从mysql数据库插入/检索数据。 刚启动时有两个按钮:查找和重置。它们都工作正常但是当我点击FIND而字段为空时会出现这些错误:
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
这是myclass.php
件:
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);
和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>
我尝试通过添加
来解决这个问题 if($result === FALSE){
die(mysql_error());
}
在我的while循环之前但它没有帮助。希望如果在空字段上运行查询,将显示消息“插入值”。有什么建议???高度赞赏
那就是查询:
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);
}
答案 0 :(得分:1)
问题是您正在尝试执行空查询。在执行生成的查询(可能为空)之前检查这种情况;
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);
}