I have a method named getUserIds in a class called Db.php.
public function getUserIds() {
$connection = $this -> connect();
return $this -> select("select distinct user_id from users");
}
When I call the function in a file located in the same folder as Db.php I get
PHP Fatal error: Call to undefined function getUserIds()
The file generating the error looks like this:
<?php
require('Db.php');
$db = new Db();
$userIds = $db -> getUserIds();
echo '<select>';
echo '<option value="">Choose your User Id</option>
while($userId = mysqli_fetch_assoc($userIds)) {
echo "<option>$userId</option>";
}
echo '</select>';
?>
Here is the contents of Db.php:
class Db {
// The database connection
protected static $connection;
/**
* Connect to the database
*
* @return bool false on failure / mysqli MySQLi object instance on success
*/
public function connect() {
// Try and connect to the database
if(!isset(self::$connection)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('./config.ini');
self::$connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if(self::$connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return false;
}
return self::$connection;
}
/**
* Query the database
*
* @param $query The query string
* @return mixed The result of the mysqli::query() function
*/
public function query($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query);
return $result;
}
/**
* Fetch rows from the database (SELECT query)
*
* @param $query The query string
* @return bool False on failure / array Database rows on success
*/
public function select($query) {
$rows = array();
$result = $this -> query($query);
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
/**
* Fetch the last error from the database
*
* @return string Database error message
*/
public function error() {
$connection = $this -> connect();
return $connection -> error;
}
/**
* Quote and escape value for use in a database query
*
* @param string $value The value to be quoted and escaped
* @return string The quoted and escaped string
*/
public function quote($value) {
$connection = $this -> connect();
return "'" . $connection -> real_escape_string($value) . "'";
}
public function getUserIds() {
$connection = $this -> connect();
return $this -> select("select distinct user_id from users");
}
}
var_dump($db);immediately after creating it?getUserIds()does not exist in your class, that is why youre getting that error