mysqli - fatal error : Call to a member function query() on a non-object in

标签 mysqli php

fatal error :在线非对象上调用成员函数 query(): $result = $conn->query($sql) 或 die(mysqli_error());

谁知道出了什么问题以及如何修复它?

<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
  $host = 'localhost';
  $db = 'phpsols';
  if ($usertype  == 'read') {
    $user = 'psread';
    $pwd = '123';
  } elseif ($usertype == 'write') {
    $user = 'pswrite';
    $pwd = '123';
  } else {
    exit('Unrecognized connection type');
  }
  if ($connectionType == 'mysqli') {
    return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
  } else {
    try {
      return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
    } catch (PDOException $e) {
      echo 'Cannot connect to database';
      exit;
    }
  }
}

// connect to MySQL
$conn = dbConnect('read');
// prepare the SQL query
$sql = 'SELECT * FROM images';
// submit the query and capture the result
**$result = $conn->query($sql) or die(mysqli_error());**
// find out how many records were retrieved
$numRows = $result->num_rows;
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Connecting with MySQLi</title>
</head>

<body>
<p>A total of <?php echo $numRows; ?> records were found.</p>
</body>
</html>

最佳答案

罪魁祸首很可能是这一行:

return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');

do xyz or die() 构造与 return 语句结合使用会导致有趣的行为(即整个事情被解释为 OR 表达式,并且因为 new mysqli 永远不会为假,“die”永远不会被处理。)。查看类似案例here .

这样做:

$result = new mysqli($host, $user, $pwd, $db) ;
if (!$result) die (....);
return $result;

此外,稍微相关的是,我认为您永远不会捕获 PDO 连接错误,因为:

return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);

总是退出函数,并且永远不会到达catch block 。与您的实际问题一样,解决方案是首先将对象传递给 $result 变量。

关于mysqli - fatal error : Call to a member function query() on a non-object in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4633799/

相关文章:

php - 替换 mysql_real_escape_string() :

php - 使用 php 和 mysql 登录表单出错

php - 如何正确设计这些类?

php - Magento Cron Tab 作业时区

php - 如何使用 order by 左连接三个表?

PHP MySQLI 防止 SQL 注入(inject)

php - 允许的内存大小为 67108864 字节耗尽

PHP/MYSQL 帮助向所有用户(关注者)甚至数百万用户发出通知

php - 从mysql数据库获取 parent 姓名

php - MySQL php数组 - 从数组中查找与查询不匹配的值