Implementing mysqli procedural with a class - php

so recently I've been trying to use more procedural mysqli for practise, and have been looking at http://www.phpknowhow.com/mysql/mysqli-procedural-functions/, and also w3schools as reference, but i'm still having trouble so I thought I'd ask.
I have this database.php file where I have alot of stuff but the important stuff is
class Database{
public $host = DB_HOST;
public $username = DB_USER;
public $password = DB_PASS;
public $db_name = DB_NAME;
public $link;
public $error;
public function __construct(){
$this -> connect();
}
private function connect(){
$link = mysqli_connect($this->host,$this->username,$this->password,$this->db_name);
if(!$link){
echo "Failed".mysqli_error($link);
}
}
// create select method
public function select($query){
$result = mysqli_query($link,$query) or die("didnt work".mysqli_error($link));
if(mysqli_num_rows($result) > 0){
return $result;
}
else{
return false;
}
}
Now the way it currently works fine in my index.php file is simply by doing something like
$db = new Database();
//CREATe query
$query = "SELECT * FROM posts";
$posts = $db->select($query);
Is there any way to implement $posts = $db->select($query) with procedural functions? Before I have done stuff like mysqli_query($link,$query), but link is public here and inside a class so I can't do that, plus I want to access the function select . Thanks!

$link is not defined in your function select.
Modify your connect function:
private function connect() {
$this->link = mysqli_connect($this->host, $this->username, $this->password, $this->db_name);
if(!$this->link) {
echo "Failed: " . mysqli_error($this->link);
}
}
Now $this->link may be used in your select function:
public function select($query){
$result = mysqli_query($this->link, $query) or die("didn't work: " .mysqli_error($this->link));
if(mysqli_num_rows($result) > 0) {
return $result;
}
else{
return false;
}
}
I suggest you read the PHP OOP documenentation (at least the first chapters) to get a better understanding.

Related

how can i close mysql connection including DB name after execute a function using OOP

I am learning on PHP and i have a basic knowledge on php. I am facing a problem that is,
I want to clear the database connection cause i am working on a demo project for my skill improvement. But this site is to slow.So that i want to clear db connection after execute any page.I am trying last 2 days, still searching.
PLEASE HELP...
Here is my class file db_connect.php
class Db_connect {
public function database_connection() {
$host_name = 'localhost';
$user_name = 'root';
$password = '';
$db_name = 'product_management';
$db_con = mysqli_connect($host_name, $user_name, $password, $db_name);
if (!$db_con) {
die('Connection Fail' . mysqli_error($db_con));
}
return $db_con;
}
}
Here is my class file soft_info.php
which is include some function-
class Soft_info extends Db_connect{
public $link;
public function __construct() {
$this->link = $this->database_connection();
}
public function search_model_info($model_id) {
$sql = "SELECT * FROM sw_info ORDER BY s.sw_id DESC";
if (mysqli_query($this->link, $sql)) {
$query_result = mysqli_query($this->link, $sql);
return $query_result;
} else {
die('Query problem' . mysqli_error($this->link));
}
}
}
for example:
mysqli_close($this->link);
http://php.net/manual/en/mysqli.close.php

Reusing a mysql connection in oop php [duplicate]

This question already has answers here:
Use global variables in a class
(4 answers)
Closed 7 years ago.
Solution taken from comment so I can't accept an answer for this to be closed. But I did post the actual solution that works for me below
I'm new to OOP and I just can't figure out, even after reading through quite few examples, how use the same mysql connection without using $GLOBALS.
If someone can explain it like I'm a two year old that would be super helpful.
This is my connection file.
$hostname = 'hostname';
$username = 'db';
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=db", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
but then to use this in a class or a function I do this:
class basic {
function simple($id) {
$query = $GLOBALS['dbh']->query("SELECT * FROM table WHERE id = $id");
$row = $query->fetch(PDO::FETCH_OBJ);
$thing = $row->partoftable;
echo $thing;
}
}
$first = new basic();
$first->simple(12);
This of course will return what I'm looking for the $thing with the id of 12. But how do I do this without the GLOBALS['dbh'] to connect to the db?
Also feel free to rip anything else apart but just keep in mind this was the easiest example of what I'm talking about.
Thanks in advance.
This is the solution that works for me based on the comment below.
class basic {
function __construct($dbh)
{
$this->dbh = $dbh;
}
function simple($id) {
$query = $this->dbh->query("SELECT * FROM table WHERE id = $id");
$row = $query->fetch(PDO::FETCH_OBJ);
$thing = $row->partoftable;
echo $thing;
}
}
$first = new basic($dbh);
$first->simple(12);
Thanks. hope this helps someone else.
class basic {
var $CONNECTION;
function __construct($dbh) {
$this->CONNECTION = $dbh;
}
function simple($id) {
$conn = $this->CONNECTION;
$query = $conn->prepare("SELECT * FROM table WHERE id = $id");
$query->execute();
$row = $query->fetch(PDO::FETCH_OBJ);
$thing = $row->partoftable;
echo $thing;
}
}
//class ends you can use thae class like this
$hostname = 'hostname';
$username = 'db';
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=db", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$first = new basic($dbh);
$first->simple(12);
You can create a class for database connection :
class MysqlDB
{
private $conn;
public function __construct($hostName, $userName, $passWord, $databaseName)
{
$this->conn = new PDO("mysql:host=$hostName;dbname=$databaseName", $userName, $passWord);
}
public function query($id)
{
//This is just a sample query
$this->conn->query("SELECT * FROM table WHERE id = $id");
return $query->fetch(PDO::FETCH_OBJ);
}
}
And then you can use in another class like:
class basic {
private $dbConn;
function __construct(){
$dbConn = new MysqlDB('hostName', 'username', 'password', 'database')
}
function simple($id) {
$row = $dbConn->query($id);
$thing = $row->partoftable;
echo $thing;
}
}
You can also create a database connection in common class and extend it with you class
I like this solution:
class db_connection
{
public static $sql_object = NULL;
public function __construct()
{
if ($sql_object === NULL)
{
// Initialize self::$sql_object
}
}
}
Then you can use it with:
$db = new db_connection();
// Do something with $db->sql_object
Since $sql_object is static, it will be initialized only once, no matter how many times you use new db_connection().
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'db');
class DB_con {
function __construct()
{
$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASS) or die('localhost connection problem'.mysql_error());
mysql_select_db(DB_NAME, $conn);
}
public function insert($fname,$lname,)
{
$res = mysql_query("INSERT users(first_name,last_name,) VALUES('$fname','$lname')");
return $res;
}
public function select($id)
{
$res=mysql_query("SELECT * FROM users WHERE id = $id");
return $res;
}
} ?>

PHP query class not returing values

I am writing a query class for my php project, But i have a problem the query does not return any values from my DB.
PHP code:
<?php
class DatabaseConnect{
protected $host = 'localhost';
protected $user = 'root';
protected $pass = 'root';
protected $db = 'test';
public function __construct(){
$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db) or die('Cannot Connect to DB');
return $con;
}
}
class ExecuteQuery{
public $connection;
public $result;
public function __construct(){
$this->connection = new DatabaseConnect();
}
public function getQueryAction($sql){
$this->result = mysqli_query($this->connection, $sql);
}
public function setStringAction($string){
$file = file_get_contents('queryFile.json');
$json = json_decode($file, true);
foreach($json['Queries'] as $this->result){
return $this->result[$string];
}
}
}
$execute = new ExecuteQuery();
Jason file ('it will contain all the queries') :
{
"Queries": [
{"query1":"SELECT * FROM tbl_user"},
{"query2":"SELECT * FROM tbl_users WHERE status=1"}
]
}
Index file:
<?php
require_once('query.php');
?>
<html>
<head>
<title>
</title>
</head>
<body>
<h1>Welcome</h1>
<h3><?php
$execute->getQueryAction($execute->setStringAction('query1'));
foreach($execute->result as $item){
echo $item['id']. ' ' . $item['user_name'] .'<br />';
}
?></h3>
</body>
</html>
So what I do is create a class to process jason file extract a query and then class to run a query. Jason file as I mentioned holds all the queries, In index and in any file where I include query.php i can run all the queries like this:
$execute->getQueryAction($execute->setStringAction('query name'));
after some debugging I realised that the code fails in getQueryAction method, I think mysqli_query dont like $this->connection.
My questions are :
Why
and how to fix it
A constructor cannot return anything, a constructor only purpose is to create an instance of a class
private $con;
public function __construct(){
$this->con = mysqli_connect($this->host, $this->user, $this->pass, $this->db)
or die('Cannot Connect to DB');
}
public function get_connection(){
return $this->con;
}
so in ExecuteQuery class you can do:
public function __construct(){
$db = new DatabaseConnect();
$this->connection = $db->get_connection();
}
mysqli->query does not return results. It only returns a handle with which you could request the results. Look up mysqli->fetch_assoc
http://php.net/manual/en/mysqli-result.fetch-assoc.php
if ($result = mysqli_query($this->connection, $sql)) {
/* fetch associative array */
while ($item = mysqli_fetch_array($result)) {
echo $item['id']. ' ' . $item['user_name'] .'<br />';
}
/* free result set */
mysqli_free_result($result);
}
Thx for trying to help me guys, But I just managed to fixe it with minor changes here they are:
changed the method namd from __construct to DBcon under DatabaseConnection class,
then i did this in get getQueryAction:
$this->result = mysqli_query($this->connection->DBcon(), $sql);
the whole class:
class DatabaseConnect{
protected $host = 'localhost';
protected $user = 'root';
protected $pass = 'root';
protected $db = 'test';
public function DBcon(){
$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db) or die('Cannot Connect to DB');
return $con;
}
}
class ExecuteQuery{
public $connection;
public $result;
public function __construct(){
$this->connection = new DatabaseConnect();
}
public function getQueryAction($sql){
$this->result = mysqli_query($this->connection->DBcon(), $sql);
}
public function setStringAction($string){
$file = file_get_contents('queryFile.json');
$json = json_decode($file, true);
foreach($json['Queries'] as $this->result){
return $this->result[$string];
}
}
}
$execute = new ExecuteQuery();
Now everything works perfect still not sure why the previous method (present in inital question) but this works xD

PHP code convert to PHP/MySQLi OOP

today i tried to convert my code to PHP/MySQLi OOP code.
class Database
{
private $host;
private $user;
private $password;
private $db;
private $mysqli;
function __construct()
{
$this->host = "*****";
$this->user = "*****";
$this->password = "******";
$this->db = "*****";
$this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
if (mysqli_connect_errno()):
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
endif;
}
}
This is a script for the query's:
include_once("WD_Config/database.php");
class Adressen_Db
{
function __construct()
{
$this->database = new Database();
}
public function selecteer()
{
$query = "SELECT * FROM wd_adressen WHERE verborgen = 0 ORDER BY naam ASC";
$result = $this->database->mysqli->query($query);
return $result;
}
}
And this is how i call it.
$adressen = new Adressen_Db;
$adressen_result = $adressen->selecteer();
echo "<p>";
while ($row = $adressen_result->fetch_assoc()):
echo "<a href='http://maps.google.com/?q=".$row['voladres']."' target='_blank'>".$row['naam']."</a> woonachtig op <i>".$row['voladres']."</i><br>";
endwhile;
echo "</p>";
I alway get a "Call to a member function query() on a non-object". Doesn't matter what i trie ...
Can somebody tell me why that is?
Thanks!
The $mysqli variable in class Database is declared private.
You can access it only through setters and getters.
I think while you definitely need to have $mysqli as public so it can be accessed in the other method, there might be something else, as the error would be something like
trying to access private property in database class
or something like that, whereas your script throws a non-object call error
I think your new Adressen_Db; lacks the parenthesis:
$adressen = new Adressen_Db();
You can replace your code with this:
Config.php
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "your_database_name");
Now include this file in your database file
require_once 'config.php';
Class Database {
public $host = DB_HOST;
public $user = DB_USER;
public $pass = DB_PASS;
public $dbname = DB_NAME;
public $link;
public $error;
public function __construct() {
$this->getConnection();
}
private function getConnection() {
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
if (!$this->link) {
$this->error = "Connection failed" . $this->link->connect_error;
return false;
}
}
// for only select query
public function select($query) {
$result = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($result->num_rows > 0) {
return $result;
} else {
return false;
}
}
// for insert, delete and update
public function myquery($query) {
$myquery = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($myquery) {
return $myquery;
} else {
return false;
}
}
}
Now, make your queries like this:
<?php
require_once './lib/Database.php';
?>
<?php
class Admin {
private $db;
public function __construct() {
$this->db = new Database();
}
public function getData(){
$query = "SELECT * FROM admin";
$result = $this->db->select($query);
if($result != false){
while($row = $result->fetch_assoc()){
// do your thing
}
}
}
public function insert(){
$query = "INSERT INTO admin(admin_name) VALUES('$admin_name')";
$result = $this->db->myquery($query);
if($result){
$msg = "User has been added successfully.";
return $msg;
} else {
$msg = "Error while adding user. Please try again.";
return $msg;
}
}
}
Do this.

Class methods over different files

I am attempting to place a commonly used method (opendb) in the same class and file as my connect configuration file (connect.php) See fig A
class qcon{
public static $conn;
function dbcon()
{
if (empty($conn))
{
$host = 'x';
$username = 'x';
$password = 'x';
$dbname = 'x';
$conn = mysqli_connect($host , $username , $password ,$dbname) or die("Oops! Please check SQL connection settings");
}
return $conn;
}
function openDB($conn)
{
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Now I want to be able to pass the connection output of fig A so I can properly use the methods in another class file. Call it class.php. Here's one example function on class.php for viewing records. See fig. B
require_once("assets/configs/connect.php");
class dbcats {
var $conn;
function getResult(){
$result = mysqli_query($this->conn , "SELECT * from felines" );
if ($result) {
return $result;
}
else {
die("SQL Retrieve Error: " . mysqli_error($this->conn));
}
}
function closeDB() {
mysqli_close($this->conn);
}
Now, to get the call to work, Fig C below is where I'm at. I'm a tiny bit stuck.
$db1 = new qcon();
$helper = new dbcats();
$db1->openDB();
$helper = $db1;
$result = $helper->getResult();
So here we are. The logic is simple enough (I'll update the question if I'm not quite clear) So would someone advise on what amendments I need to get the call operational?
Orangepill's solution is fine and will more than likely get you going quickly. However, I would recommend making some minor alterations to your classes to allow you to more easily reuse their functionality across your programs.
Here, qcon holds your database connection information and functionality. It has a getter method, getConn() that allows you to get, and pass around that connection as you need.
class qcon
{
protected $conn;
public function __construct() { ... }
public function dbcon() { ... }
public function openDB() { ... }
public function closeDB() { ... }
public function getConn() { return $this->conn; }
}
Here's an example of an alternative dbcats class. It takes in your qcon class in part of its construction and holds it in as a protected member variable that it can use whenever it needs it. It also has getters and setters so that you can change or retrieve your database connection for this class at any time via getQConn() and setQConn().
class dbcats
{
protected $qcon;
public function __construct(qcon $q) { $this->qcon = $q; }
public function getResult() { ... }
public function getQConn() { return $this->qcon; }
public function setQCon(qcon $q) { $this->qcon = $q; }
}
It may not be the quickest fix, but I believe practices such as this will serve you better in the long-run.
From what I can see you are missing the end curly bracket } on both your classes. Everything would be much easier to see if you make the indentation correctly. That is, each time you have a left curly bracket { the following lines will be indented with one tab. Like this:
class qcon {
public static $conn;
function dbcon()
{
if (empty($conn))
{
$host = 'x';
$username = 'x';
$password = 'x';
$dbname = 'x';
$conn = mysqli_connect($host , $username , $password ,$dbname) or die("Oops! Please check SQL connection settings");
}
return $conn;
}
function openDB($conn)
{
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
} <<< Missing this one
class dbcats {
var $conn;
function getResult(){
$result = mysqli_query($this->conn , "SELECT * from felines" );
if ($result) {
return $result;
}
else {
die("SQL Retrieve Error: " . mysqli_error($this->conn));
}
}
function closeDB() {
mysqli_close($this->conn);
}
} <<< Missing this one
You need to inject an instance of the qcon class into the dbcats class.
require_once("assets/configs/connect.php");
class dbcats {
var $conn;
public function __construct(qcon $dbconn){
$this->conn = $dbconn;
}
function getResult(){
$result = mysqli_query($this->conn , "SELECT * from felines" );
if ($result) {
return $result;
}
else {
die("SQL Retrieve Error: " . mysqli_error($this->conn));
}
}
function closeDB() {
mysqli_close($this->conn);
}
}
Then when you create an instance of dbcats pass in an instance of conn like ...
$db1 = new qcon();
$db1->openDB();
$helper = new dbcats($db1);
$result = $helper->getResult();

Categories