您好我是PHP的新手,並試圖創建一個數據庫conenction,我得到一個成員函數調用查詢()對非對象錯誤:調用一個非對象錯誤的成員函數query()
我的代碼被分成兩個文件的第一個文件包含函數用於創建connction:
<?php
function dbConnect($usertype, $connectionType = 'mysqli'){
$host = 'localhost';
$db = 'phpsols';
if($usertype == 'read'){
$user = 'psread';
$pwd = 'Alexandru&Mada';
}elseif ($usertype == 'write'){
$user = 'pswrite';
$pwd = 'Alexandru&Mada';
}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;
}
}
}
?>
在這種方法被稱爲第二個文件,但它也引發一個錯誤調用一個成員函數查詢()on non object:
<?php
require_once ('../includes/connection.inc.php');
$conn = dbConnect('read');
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error()); //error is thrown here
$numRows = $result->num_rows;
?>
我在這裏做錯了什麼?
請確認安裝了PDO和mysqli。 –
他們都安裝 –