Query after connecting to remote MySQL database using mysqli_real_connect - php

I can successfully connect to a remote MySQL database using mysqli_init(), mysqli_ssl_set and mysqlii_real_connect. I can't seem to find an example of a query being done after connecting. The result of mysqli_real_connect is a boolean value, whereas mysqli_connect returns an object representing the connection to the MySQL server. How do I refer to the connection after using mysqli_real_connect? Can anyone provide an example?
<?php error_reporting(E_ALL);
ini_set("display_errors", "1");
$obj = mysqli_init();
mysqli_options($obj, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
mysqli_ssl_set( $obj,
NULL,
NULL,
'ca-cert.pem',
NULL,
NULL);
$link = mysqli_real_connect($obj, 'xxxxxxxxxxxx.com', 'user', 'password, 'database_name');
if (!$link)
{
die('<br /><br />Connect Error (' . mysqli_connect_errno() . ') '.mysqli_connect_error());
} ?>

The way that you'd do it using your example is mysqli_query($obj, QUERY HERE);
However, you should consider using the OOP (Object Orientated Programming) style, as that would be easier for you to reference within the future.
<?php
Class Database {
private $obj;
public function __construct() {
$this->obj = new mysqli('xxxxxxxxxxxx.com', 'user', 'password', 'database_name');
if (!$this->obj) {
die('<br /><br />Connect Error (' . mysqli_connect_errno() . ') '.mysqli_connect_error());
}
}
public function query($query) {
return $this->obj->query($query);
}
}
?>
You would call this class by doing:
$db = new Database();
And from there on, you could simply call your function by using the following example.
$db->query("SELECT * FROM users"); // or whatever query you are parsing.

Related

Storing mysqli connection in object

I am trying to contain my mysqli object within a class, that other objects/scripts can use. I initialize it like so:
$this->host = $Host;
$this->username = $UName;
$this->password = $PWord;
$this->database = $DBName;
$this->debugEmail = $debugEmail;
// Create sql handler
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->database);
// Check connection
if ($this->conn->connect_error) {
die("Connection Failed: " . $this->conn->connect_error());
}
The problem is when I use this object elsewhere, it seems to think that the conn object is null.
For example:
$sqlObj = new sqlObject();
$sqlObj->init();
// run query
$sql = "SELECT * FROM table";
$result = $sqlObj->getConn()->query($sql);
It returns:
Call to a member function query() on a non-object
Certainly $sqlObj->getConn() is returning null or false (or another object) that isn't the desired type.
I recommend you to throw a new error in getConn() and wrap with a try/catch block. In this throw, return the error coming from getConn and you'll be able to understand it better. BTW, Are the connection params ok ? It seems to be something related to this.

Cannot call MySQL when including class in PHP

I've got a problem with include. I'm doing some kind of blog, and at this moment it looks like this:
index.php
article.php
class/art.class.php
Let's focus on article.php, which looks like this:
<?php
$mysqli = new mysqli("","","",""); // here are my connection details
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$mysqli->query("SET NAMES 'utf8'");
require("class/art.class.php");
$art = new Article();
print_r($art->get_art(trim($_GET['id'])));
$mysqli->close();
?>
And art.class.php is like this:
<?php
class Article {
function get_art($id) {
if(!is_numeric($id)) {
header("Location: index.php");
die("<h2>ID isn't numeric, cannot go on.</h2>'");
}
if($result = $mysqli->query("SELECT * FROM `articles` WHERE id='$id';")) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$art = $row;
}
$result->close();
}
return $art;
}
}
?>
The problem is a response from MySQL. Sorry, I mean no response. And no errors. I figured out that I need to add mysql connection code to class code. But why? How I can connect once to database and call it from anywhere, even from included class?
And sorry if my english is bad..
The get_art function within the Article class does not have access to variables outside of it's scope: please see the answer here.
In order to fix your issue, you may provide access to the $mysqli object by passing it to the constructor of the Article class when you instantiate it:
Article.php:
$mysqli = new mysqli("","","",""); // your connection details
$art = new Article($mysqli);
art.class.php:
class Article {
protected $mysqli;
public function __construct($mysqli) {
$this->$mysqli = $mysqli;
}
function get_art($id) {
// Replace $mysqli with $this->mysqli everywhere you need to
// make database calls
}
}
Although some would recommend that you avoid doing so, you could use PHP's $GLOBALS variable to store your database connection:
$mysqli = new mysqli("","","",""); // here are my connection details
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$GLOBALS['mysql'] = $mysqli;
This way you would have access to it within your class:
class Article
{
function get_art($id)
{
$mysqli = $GLOBALS['mysqli'];
...
}
}

How do I make $con available as a parameter of $Query?

I can get by with editing procedural PHP (just), but OOP is a different thing. So I'm not that experienced with what I'm doing here, but I'm trying my best...
I have a file called Quote.object.php containing the following:
$Query = new DbQuery( "INSERT", "quotes", $array );
$this->id = mysqli_insert_id();
mysqli_insert_id needs to be fed a DB connection parameter, but I'm not sure how to do it. There is another file called Mysql.handler.php containing the database connection variable - is there a way that I can make $con available as a parameter of $Query above?
class DbQuery extends DbConnectionInfo{
// file: includes/classes/MysqlQuery.php
// contains functions needed to perform queries on mysql database and functions for necessary data processing for application
// SELECT = new DbQuery("select", table,cols[$value] ,where[$col=$value],order[$value],limit);
// INSERT = new DbQuery("insert", table, data[$col=$value]);
// UPDATE = new DbQuery("update", table, data[$col=$value],where[$col=$value],limit);
// set testing as true for SQL reports in page
var $results;
var $sql;
function __construct($mode,$table = '',$var1 = '',$var2 = '',$var3 = '',$var4='')
//connects to database according to info in DbConnectInfo, runs query, closes connection
{
$temp = '';
$con = mysqli_connect($this->host, $this->user, $this->pass) or die ('There was a problem connecting to the database ' . (ENVIRONMENT == 'Development' ? mysqli_error() . "$this->user, $this->pass, $this->host" : ''));
mysqli_select_db($con,$this->db) or die ('There was a problem connecting to the database' . (ENVIRONMENT == 'Development' ? mysqli_error() : ''));
I'm trying to get $con from DbQuery so I can put it into mysqli_insert_id(). I assume that's what I need? Is there a way to get $con from DbQuery and put into mysqli_insert_id()? Or do you need more information to know this?
NB I've tried to be concise in trying to show just relevant information, apologies if I've missed other helpful info.
You're defining an object, so make $con a class variable, e.g.
function __construct() {
$this->con = mysqli_connect(...);
^^^^^^^----store in object
}
function foo() {
$result = mysqli_query($sql, $this->con);
^^^^^^^^---retrieve from object
}

Call a method to connect to the DB with mysqli

Hi i am trying to move from MySQL to MySQLi in my PHP script, i had this system class with the function that connects to the database that i call whenever i need, with a simple method like this:
Sys::database_connect();
the actual code of the function is:
function database_connect(){
require 'conf.php';//configuration file with database variables (sql_)
mysql_connect($sql_serv, $sql_user, $sql_pw) OR die('ERRO!!! não ligou a base de dados');
mysql_select_db($sql_bd);
}
after calling the function i can query the database without problem.
But I cant do the same with mysqli if I put this in the sys class:
function database_connect(){
require 'conf.php';
$mysqli = new mysqli($sql_serv, $sql_user, $sql_pw, $sql_bd);
if (mysqli_connect_errno()) {
printf("Ligação à Base de dados falhou: %s\n", mysqli_connect_error());
exit();
}
}
When I call
Sys::database_connect();
it connects to the database but i can't query has i used to what i would like would be a simple method as I have done with normal MySQL, if somebody can explain what am I doing wrong or why exactly I cannot do it like that...
Thank you in advance;
Fernando Andrade.
Your later queries have to use the mysqli connection identifier, you create when connecting to the database. So save this to a property of your system class and use it later on.
function database_connect(){
require 'conf.php';
$mysqli = new mysqli($sql_serv, $sql_user, $sql_pw, $sql_bd);
if (mysqli_connect_errno()) {
printf("Ligação à Base de dados falhou: %s\n", mysqli_connect_error());
exit();
}
Sys::$dbConn = $mysqli;
}
and then later on
function query( $sql ) {
Sys::$dbConn->query( $sql );
// error handling etc.
}
I wrote an extend for the mysqli database class
class database extends mysqli {
function __construct() {
parent::__construct('host', 'user', 'password', 'database');
if(mysqli_connect_error()) {
die('Connect error ('.mysqli_connect_errno().')'.mysqli_connect_error());
}
parent::query("SET NAMES 'utf8'");
}
function query($query) {
$result = parent::query($query);
if(!$result) {
echo "<strong>MySQL error</strong>: ".$this->error."<br />QUERY: ".$query;
die();
}
if(!is_object($result)) {
$result = new mysqli_result($this);
}
return $result;
}
}
So connecting to database is $db = new database()
Executing a query is $db->query(YOUR QUERY);

PHP Function Accessing Database Connection

How do I allow a function to access a database connection without using GLOBAL?
config.php
DEFINE ('DB_HOSTNAME', 'hostname');
DEFINE ('DB_DATABASE', 'database');
DEFINE ('DB_USERNAME', 'username');
DEFINE ('DB_PASSWORD', 'password');
$dbc = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(!$dbc) die("Unable to connect to MySQL: " . mysqli_error($dbc));
functions.php
function something()
{
$info = mysqli_query($dbc, "SELECT info FROM text") or die("Error: ".mysqli_error($dbc));
}
The above gives me the following error:
mysqli_query() expects parameter 1 to be mysqli, null given in
Use function parameters
function something ($dbc) {
// your db code here
}
function arguments
Either pass the database handle to your function, as #KingCrunch and others have said, or call a function that returns the handle:
In config.php:
function get_dbc() {
$dbc = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(!$dbc) die("Unable to connect to MySQL: " . mysqli_error($dbc));
return $dbc;
}
In functions.php:
require_once('config.php');
function something()
{
$dbc = get_dbc();
$info = mysqli_query($dbc, "SELECT info FROM text") or die("Error: ".mysqli_error($dbc));
}
You may wish to look at The mysqli Extension and Persistent Connections for details on how you can prevent the connection from being re-established on each call to get_dbc(). There are alternative approaches to this, such as creating a singleton class for your database connection.
There are two ways one is by passing arguments and the other by using function closure like #Ondrej said. But I wonder both of these require you to modify the code if that is the case, then I would suggest you to use global keyword.
You can use global keyword to get the scope of variable $dbc
Try this..
function something()
{
global $dbc;
$info = mysqli_query($dbc, "SELECT info FROM text") or die("Error: ".mysqli_error($dbc));
}
(OR)
Try this...
function something()
{
$dbc = func_get_arg(0);
$info = mysqli_query($dbc, "SELECT info FROM text") or die("Error: ".mysqli_error($dbc));
}
& do this ....
$query = something($dbc);
There are more ways. You could use classic procedural style:
function something($dbc)
or anonymous function (if you use PHP5.3):
$fn = function() using ($dbc)
its so simple just pass your $conn variable into another calling function(instead of making new connection) like
yourpage.php
$conn = new mysqli($servername, $username, $password, $dbname);
someFunction ($conn)//you can add other parameters if you like
function someFunction ($conn) {
$result = mysqli_query ($conn, "SELECT * FROM examples);
}
Note:This is not good practice to always make new connection for database access.so always make connection once and use it every where.(but if your requirement different and require multiples connections then you can make multiples connections)

Categories