Mysql工作,但期望一个布尔值

时间:2013-12-16 05:44:14

标签: php mysqli

我是PHP的新手,我正在尝试编写数据库代码。整个代码工作正常,但我得到这个布尔错误。我得到$结果期待一个布尔值。有趣的是我正在完全关注视频但出现了错误。希望有人可以向我解释这个错误意味着什么,以及我如何解决它。

错误: SUCCESS!

警告:mysqli_fetch_assoc()要求参数1为mysqli_result,布尔值在第66行的C:\ xampp \ htdocs \ introduphp \ DataBaseTut3.php中给出

警告:mysqli_free_result()要求参数1为mysqli_result,在第77行的C:\ xampp \ htdocs \ introduphp \ DataBaseTut3.php中给出布尔值

我的代码:

<?php
//1.Create database connection
$dbhost = "localhost";
$dbuser = "weekeong";
$dbpass = "alexsage";
$dbname = "fyp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//Test if connection occurred.
if(mysqli_connect_errno()) {
    die("Database connection failed: ".
    mysqli_connect_error() .
    " (" . mysqli_connect_errno(). ")"
    );
}
?>

<?php
//2. Perform database query

// these are often form values in $_POST
$id = 5;
$name = "John xan";
$age = 30;
$birthdate = "19/03/1994";
$medical_allergies = "";
$phone = 88888888;
$address = "lame street";
$doctor_assigned = "Dr Lee";


$query = "INSERT INTO patients (";
$query .= " id, name, age, birthdate, medical_allergies, phone, address, doctor_assigned";
$query .= ") VALUES (";
$query .= " {$id}, '{$name}', {$age}, '{$birthdate}', '{$medical_allergies}', {$phone}, '{$address}', '{$doctor_assigned}'";
$query .= ")";



//query is not only to get something but to get sqli to do something for us so we still use query
$result = mysqli_query($connection, $query);
//Test for query error
if ($result) {
    echo "SUCCESS!";
    //success
    //redirect_to ("somepage.php");
} else {
    //Failure
    //$message = "Creation failed";
   die("Database query failed." .mysqli_error($connection));    
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Database 3</title>
</head>

<body>

<ul>

<?php
//3 Use returned data (if any)
while($doc = mysqli_fetch_assoc($result)) {  // only creates row if there are results
// cannot use for each with fetch_row as it is not a PHP array, it is a result set from MY SQL. For Each will try to increment pointer at the end but MYSQL doesnt have array pointer so use while.
    //output data from each row
?>  
   <li><?php echo $doc["name"]; ?></li>
   <?php
}
?>
</ul>
<?php
//4. Release returned data
mysqli_free_result($result);
?>
</body>
</html>
<?php
//5. Close database connection
mysqli_close($connection);
?>

1 个答案:

答案 0 :(得分:0)

$queryINSERT语句,但是您尝试循环结果。 INSERT语句后没有要循环的行。听起来你想先运行另一个SELECT

来自the manual page regarding mysqli_query()(强调补充):

  

失败时返回FALSE。对于成功的SELECT,SHOW,DESCRIBE或EXPLAIN查询,mysqli_query()将返回一个mysqli_result对象。 对于其他成功的查询,mysqli_query()将返回TRUE。

在您的情况下,如果$result有效,则truefalse,如果不有则为{{1}}。无论哪种方式,都没有要循环的行。