How to get database object out of function - php

I have a function that connects to a database. After I call the function, I want it to return the database/connection object so that I am able to then use that object and perform queries on the database. How can I return the object below $mysqli from the function test() so that I can use $mysqli outside the function, and even in different scripts. Or should I write a specific function for each query?
function test($user, $pass, $db, $host){
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else {
echo 'Checkpoint 1 <br>';
return $mysqli;
}
}
test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli->query($sql);

What I use for writing big projects is the following:
Class MySQL
{
protected $_conn;
public function __construct() {
$this->_DB_NAME = DB_NAME;
$this->_DB_USER = DB_USER;
$this->_DB_PASS = DB_PASSWORD;
$this->_DB_HOST = DB_HOST;
$this->_conn = mysqli_connect($this->_DB_HOST, $this->_DB_USER, $this->_DB_PASS);
if(!$this->_conn) {
die('A problem has occured');
}
}
public function connect() {
if(!mysqli_select_db($this->_conn, $this->_DB_NAME)) {
die("1st time failed<br>");
}
return $this->_conn;
}
}
Class Database
{
protected $_conn;
public function __construct() {
$db = new MySQL;
$this->_conn = $db->connect();
}
public function retrieve() {
$result = $this->_conn->query("SELECT * FROM mytable");
return $result;
}
}
$database = new Database();
$result = $database->retrieve();

You can simply use global variable
$mysqli = null;
function test($user, $pass, $db, $host){
// Here you define variable in function to global
global $mysqli;
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else{
echo 'Checkpoint 1 <br>';
return $mysqli;
}
}
test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli->query($sql);

Related

PHP - Call to a member function query() on null - Error [duplicate]

This question already has answers here:
Fatal error: Call to a member function query() on null
(2 answers)
Closed 5 years ago.
I have the following code in php for connecting to my database:
<?php
class MY_SQL{
private $username;
private $password;
private $conn;
public function __construct($SERVERNAME){
$this->username = "username";
$this->password = "password";
if($SERVERNAME == "data_"){
$server = "Servername";
}
else {
$server = $SERVERNAME;
}
// Create connection
$conn = new mysqli($server, $this->username, $this->password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
public function SQLCommand($cmd) {
if ( $this->conn->query($cmd) === TRUE ) {
echo "New record created successfully";
} else {
echo "Error: " . $cmd . "<br>" . $conn->error;
}
}
}
$sql = "INSERT INTO _test(test1, test2) VALUES ('hello','hi');";
$database = new MY_SQL("Servername");
$database->SQLCommand($sql);
?>
I get the following error:
Fatal error: Call to a member function query() on null
What is going wrong?
$this->conn = $conn; in __construct()
I would suggest you to improve your class with this example (taken from https://github.com/opencart/opencart/blob/master/upload/system/library/db/mysqli.php)
final class My_SQLi
{
private $connection;
public function __construct($hostname, $username, $password, $database, $port = '3306')
{
$this->connection = new \mysqli($hostname, $username, $password, $database, $port);
if ($this->connection->connect_error) {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno);
}
$this->connection->set_charset("utf8");
$this->connection->query("SET SQL_MODE = ''");
}
public function query($sql)
{
$query = $this->connection->query($sql);
if (!$this->connection->errno) {
if ($query instanceof \mysqli_result) {
$data = array();
while ($row = $query->fetch_assoc()) {
$data[] = $row;
}
$result = new \stdClass();
$result->num_rows = $query->num_rows;
$result->row = isset($data[0]) ? $data[0] : array();
$result->rows = $data;
$query->close();
return $result;
} else {
return true;
}
} else {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno . '<br />' . $sql);
}
}
public function escape($value)
{
return $this->connection->real_escape_string($value);
}
public function countAffected()
{
return $this->connection->affected_rows;
}
public function getLastId()
{
return $this->connection->insert_id;
}
public function isConnected()
{
return $this->connection->ping();
}
public function __destruct()
{
$this->connection->close();
}
}
$sql = "INSERT INTO _test(test1, test2) VALUES ('hello','hi');";
$mysql = new My_SQLi('host', 'user', 'password', 'db');
$result = $mysql->query($sql);

Cannot retrieve records using the database class.

This is a database class which connects to the database taking in the host name, username, password and the databasename. The MembersModel class after the DatabaseConnect class, which also extends the DatabaseConnect, is supposed to retrieve information.
<?php
class DatabaseConnect
{
protected $conn;
protected $host, $username, $password, $database;
public function __construct($host, $username, $password, $database){
// Create connection
$this->conn = new mysqli($host, $username, $password,$database)
OR die("There was a problem connecting to the database");
return true;
}
public function query($sql) {
$result = $this->conn->query($sql);
if (!$result) {
die('Invalid query:');
}
return $result;
}
public function __destruct(){
$this->conn->close()
OR die("Problem disconnecting from the database");
}
}
class MemberModel extends DatabaseConnect
{
public function getAllMembers() {
$result = $this->query("SELECT * FROM members");
return $result;
}
}
To connect and retrieve from the database this is what I have been trying to do
$db = new DatabaseConnect("localhost", "root", "", "pcaframework");
$allMembers = $db->getAllMembers();
while ($row = mysqli_fetch_assoc($allMembers)) {
echo "First Name: " . $row['name'] ."<br />";
echo "Last Name: " . $row['email'] ."<br />";
echo "<hr />";
}
but this is what I get "Fatal error: Call to undefined method DatabaseConnect::getAllMembers()". Can you point out the problem here.
Your $db object should be an instance of MemberModel. The DatabaseConnect class does not contain the getAllMembers function.
Change
$db = new DatabaseConnect("localhost", "root", "", "pcaframework");
To
$db = new MemberModel("localhost", "root", "", "pcaframework");

function within a function returning an object not working

I have some code which works:
$user = 'xxx';
$pass = 'xxx';
$db='vive';
$host ='localhost';
$name = 'chris';
function test($user, $pass, $db, $host){
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else{
echo 'Checkpoint 1.0 <br>';
return $mysqli;
}
}
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0) ...
I am able to connect to the database and pull the information that I want out of the database everytime. I wanted to clean up my code a little (all the details are not shown), so i made a new function register() out of the last part of the code. In this new function, i want to call on function test() to return me a database connection object which I can then use to perform queries:
<?php
$user = 'root';
$pass = 'root';
$db='vive';
$host ='localhost';
$name = 'chris';
function test($user, $pass, $db, $host){
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else{
echo 'Checkpoint 1.0 <br>';
return $mysqli;
}
}
function register($name){
echo'test';
global $user;
global $pass;
global $db;
global $host;
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0)...
}
For some reason the function register() will never give me any values from the database. I am unable to get anything for $result. Any help is appreciated, I have been dancing around the problem for a few days now. Note that in my actual code I have these two functions in different php files.
The LIKE statement there in the query is missing %...% wrapper.
change the register to :
function register($name){
global $user;
global $pass;
global $db;
global $host;
$name = "%".$name."%"; // see here..
echo'test';
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0)...
}
and make sure the method is called
Why the where username like?
shouldn't it be where username = ?
also the quotes you used are redundant.
$sql = "SELECT * FROM vive_user WHERE username LIKE"."'$name'";
could just be
$sql = "SELECT * FROM vive_user WHERE username = '$name'";

Connect to DB and Activites by OOP in PHP

Hi I am having some issues connecting to my DB using OO PHP. My script is below. I have been going at this for a while now. This is just a test script as I am fairly new to OOP. Please don't be harsh
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$mysqli = new mysqli($host, $username, $password, $db);
if (!$mysqli){
echo "error in connecting to database";
}
else{
echo "success in connecting to database";
}
}
public function query(){
$result = $mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
Usage...
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
Your main problem is that you aren't storing a value into your class' $mysqli property. You need to use $this->mysqli in your constructor and query method instead of $mysqli.
Secondly, this class adds nothing that the mysqli class doesn't already have. You might as well simply use
$DB = new mysqli('localhost', 'root', 'xxxx', 'yyyy');
if ($DB->connect_error) {
throw new Exception($DB->connect_error, $DB->connect_errno);
}
The problem is, you are accessing the class property without $this. The $mysqli should be in $this->mysqli in constructor function.
You are using mysqli property as Object of mysqli class.
Then you can use the query function of mysqli property object(In Database class) by $this->mysqli->query("SELECT * FROM inventory") in query function.
Updated Code:
<?php
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->mysqli = new mysqli($host, $username, $password, $db);
/* check connection */
if ($this->mysqli->connect_errno) {
printf("Connect failed: %s\n", $this->mysqli->connect_error);
exit();
} else {
echo "success in connecting to database";
}
}
public function query(){
$result = $this->mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
Try this:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_error()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}

Database connection using php class and methods

Here is mycode dbclass.php i am new for oops concept,
<?php
class Database {
private $link;
private $hostname, $username, $password, $dbname;
public function __construct( $hostname, $username, $password, $dbname ) {
$this->link=mysql_connect($this->hostname,$this->username,$this->password) or die("Mysql Connection error!!");
mysql_select_db($this->dbname,$this->link) or die("error:".mysql_error());
return true;
}
public function query( $query ) {
$result = mysql_query( $query );
if ( !$result ) {
die('Invalid query: ' . mysql_error());
}
return $result;
}
public function __destruct() {
mysql_close($this->link) or die("Error:".mysql_error());
}
}
?>
<?php
include("dbclass.php");
$db = new Database("localhost", "root", "password", "test");
$result = $db->query("select * from messages");
while ( $row = mysql_fetch_array( $result ) ) {
echo $row['id'];
}
?>
if i run this code it showing database not connected. I don't know why?
The problem is here :
$this->link=mysql_connect($this->hostname,$this->username,$this->password)
You are not assigning the argument in function to your variables of class. Hence do this
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
and then give:
$this->link=mysql_connect($this->hostname,$this->username,$this->password);

Categories