Reputation: 35
This is simple stuff and I saw a lot of similar things but nothing that basic. When trying to set up an OOP MySQLi connection using the following code:
<?php
$link = new mysqli('localhost', 'root', '');
if (!$link) {
die('Connection Failed: '. $link->error());
}
$sql = "SELECT artist_name FROM artists";
$result = $link->query($sql);
while ($row = $result->fetch_assoc()) {
printf('Artist: %s<br />', $row['artist_name']);
}
$result->close();
$link->close();
I get the following error the $result->fetch_assoc()
Fatal error: Call to a member function query() on a non-object in
C:\xampp\htdocs\PHPbook\chapter4\test2.php on line 9
I tried some stuff and found out $link
is indeed an object but $result
is a boolean.
This bit of code is taken from a book I'm reading from and wondered if anything changed since the book was written.
Thank you for your help
Upvotes: 1
Views: 61
Reputation: 16253
You have no connection to a database. See Call to member function query() on a non-object
tells you that the method call query
can't be executed because link
doesn't have that method yet available for you. Simply select a database and check that you actually have a real connection to that database.
<?php
$link = new mysqli('localhost', 'root', '', 'db_name');
if ($link->connect_error === true) {
trigger_error('No Connection', E_USER_ERROR);
}
// Continue with your logic ...
Upvotes: 0
Reputation: 16828
You forgot to select the database:
mysqli_select_db($link, 'DATABASE_NAME');
Upvotes: 1