Reputation: 5183
I was trying to make a database class similar to what most cms have, so I am making a connection in one function and returning connection object to be used for queries in other functions in class ..
<?php
class my_database {
var $host = 'localhost';
var $user = 'prince';
var $pass = 'abcd1234wxyz';
var $db = 'world';
function __construct() {
$this->db_connect();
}
function db_connect() {
$mysqli = mysqli_connect($host,$user,$pass,$db);
/* check connection */
if (!$mysqli) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli;
}
function query($query) {
$mysqli = $this->db_connect();
if ($result = mysqli_query($mysqli, $query)) {
while ($row = mysqli_fetch_row($result)) {
echo "<pre>";
print_r($row);
echo "</pre>";
}
mysqli_free_result($result);
} else
echo "fails"; exit;
}
}
$database = new my_database;
/*************** Class Ends ****************************/
function get_results() {
global $database;
$database->query("select * from city limit 10");
}
get_results();
?>
It always output fails
, I Am new to Oops & mysqli maybe I am missing something obvious.
Please help !
Upvotes: 0
Views: 1499
Reputation: 187
Your class is in many ways a bad practice. First of all, you are using the old PHP4 syntax here, which is already unsupported. It is highly recommended to switch over to PHP5 (https://www.php.net/manual/en/language.oop5.php).
Secondly, I would use PDO rather than MySQLi. However, whichever of these you use, they already have an object orientated interface. So why using the procedural? -> https://www.php.net/manual/en/class.mysqli.php (MySQLi)
https://www.php.net/manual/en/book.pdo.php (PDO)
Regarding your implementation, there are also some really bad practices.Just have a closer look on your db_connect() function: This is called whenever you use the query() method, meaning, you creconnect each time you do a query! This is useless, you only need one connect per request! The solution to this is an object property which holds the open database-connection.
On top of that, in your code at the bottom you break some key concepts of OOP when using "global". Go ahead and use Dependency Injection instead, meaning to literally inject the $database object to your function ( function(my_database $db) {} ).
There are tons of implementations of what you're doing on the internet, just use google ;)
Upvotes: 1
Reputation: 13725
A few issues:
(Otherwise there are lots of free db layer for php. for example adodb.)
Upvotes: 1