PHP Function Accessing Database Connection - php

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)

Related

PHP : Make other functions access the $conn variable inside my database connection function

Make other functions access the $conn variable inside my database connection function
So here I am absolutely desperate trying to make something work. I know what im trying to do is not OOP neither 100% best practice. It is not for a live website, I am just learning some basic PHP concepts on XAMPP.
What I am trying to do is to make the $conn variable inside my database connection function accessible to all other functions that need it. I am thinking of passing it as a parameter, but how can this be done? I prefer not using PHP's "global" or $GLOBALS. My method of working right now is with mysqli using procedural methods.
For example I have something like this:
function db () {
$conn = mysqli_connect ("localhost", "root", "", "database");
}
function someFunction () {
$result = mysqli_query ($conn, "SELECT * FROM examples)
}
I never found the answer to my issue...most solutions which I recently got familiar with are OOP based or use somewhat questionable methods.
------------------------------------------------------------------------------------------------------------------------------------
SOLUTION A - I would rather avoid not having my connection in a wrapper and using global variables:
global $conn = mysqli_connect ("localhost", "root", "", "database");
global $conn;
function someFunction () {
global $conn;
$result = mysqli_query ($conn, "SELECT * FROM examples)
}
SOLUTION B - I am not ready for OOP yet but I know this works. The point is I want to learn something different:
class Database
{
private static $conn;
public static function getObject()
{
if (!self::$conn)
self::$conn = new mysqli("localhost", "root", "", "database");
return self::$conn;
}
}
function someFunction () {
$result = mysqli_query (Database::$conn, "SELECT * FROM examples)
}
SOLUTION C - Not using functions at all...just keeping it unwrapped which I dont find very practical in the long term:
$conn = mysqli_connect ("localhost", "root", "", "database");
$result = mysqli_query ($conn, "SELECT * FROM examples)
------------------------------------------------------------------------------------------------------------------------------------
THE SOLUTION I AM TRYING TO ACHIEVE:
function db () {
$conn = mysqli_connect ("localhost", "root", "", "database");
return $conn;
}
function someFunction () {
$conn = db ();
$result = mysqli_query ($conn, "SELECT * FROM examples)
}
OR Something like this where I just pass in the connection as a parameter or something (pseudo code at the moment)
function db () {
$conn = mysqli_connect ("localhost", "root", "", "database");
}
function someFunction ($conn) {
$result = mysqli_query ($conn, "SELECT * FROM examples)
}
------------------------------------------------------------------------------------------------------------------------------------
So how do I achieve something like the last two but which actually works. Is this concept possible?
Your Desired Solution: This should work, and you'll only make one connection.
function db () {
static $conn;
if ($conn===NULL){
$conn = mysqli_connect ("localhost", "root", "", "database");
}
return $conn;
}
function someFunction () {
$conn = db();
$result = mysqli_query ($conn, "SELECT * FROM examples);
}
If you used the function someFunction($conn), that would make your code much messier, since you wouldn't actually have universal access to $conn from anywhere.
You should go with Solution B IMO. That way, you can have simple access to it Database::$conn which will be consistent throughout your script. You could should have an initialize function (you could use a different name if you want) that will initialize Database::$conn, and you can then use that to initialize other things on the Database class later, if desired.
Solution A is terrible. I did that for a long time (globalizing things), and it was a horrible idea. I should have never done that. But I did. And I learned. It just made code get progressively sloppier and sloppier.
Solution B: Database::$conn should be public if you want to be able to access it by Database::$conn from anywhere. If it's private, then you would always need to call Database::getObject();
Solution C: You're right. That would be very impractical.
Solution B rewrite:
class Database
{
/** TRUE if static variables have been initialized. FALSE otherwise
*/
private static $init = FALSE;
/** The mysqli connection object
*/
public static $conn;
/** initializes the static class variables. Only runs initialization once.
* does not return anything.
*/
public static function initialize()
{
if (self::$init===TRUE)return;
self::$init = TRUE;
self::$conn = new mysqli("localhost", "root", "", "database");
}
}
Then... call Database::initialize() at least once before it gets used.
<?php
Database::initialize();
$result = mysqli_query (Database::$conn, "SELECT * FROM examples);
?>
EDIT
You can also call Database::initialize() immediately after the declaration of the class, in that PHP file. Then initializing is handled.
I'm now far more fond of something like Database::getDb() than accessing the $conn property directly. Then initialize can be called from the getDb() function. Basically like the Desired Solution but inside a class. The class really isn't necessary, but it can be nice if you like classes, like I do.
All of the answers in this section are overkill as they are doing overhead just by creating a wrapper around a database object.
For separation of concern(Maintainability) use a separate PHP file for database connection and use require_once.
//Inside Database_Connect.php
$db = mysqi_connect(localhost, database, password);
Now use $GLOBALS['db'] inside your mysqli_ functions wherever needed.
OR, initialize your script / object as
$dbConn = $GLOBALS['db'];
and use $dbConn inside your mysqli_ functions wherever needed.
simple answer 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)
Pass an argument to your function like and return the connection
function db($conn){
$conn = mysqli_connect ("localhost", "root", "", "database");
return $conn;
}
If you have multiple php files which require db access, then the option you can have is create a file connection.php with connection code
<?php
$conn = mysqli_connect ("localhost", "root", "", "database");
?>
And use include_once 'connection.php'; in all other files you require a connection.

PHP: Can not use global variable in function to connect mysqli

I've been searching stack to get my answer, but nothing fixed my problem. So here's my shot:
$conn = mysqli_connect('localhost', 'username', 'pass', 'db');
function GetArticle() {
global $conn;
$sql = "sql query";
$getresult = mysqli_query($conn, $sql);
..
}
This doesn't seem to work. If I put $conn inside the function, it works fine.
Any ideas?
I don't know your exact situation, but in general I do not see the benefit to using $conn as global. Your function depends on a mysqli connection in order to work, so just make the connection a function parameter.
function GetArticle($conn) {
$sql = "sql query";
$getresult = mysqli_query($conn, $sql);
..
}
Then after you have established your connection, you can call the function with your connection object as its argument.
$conn = mysqli_connect('localhost', 'username', 'pass', 'db');
$article = GetArticle($conn);
I think this is a more manageable approach than trying to keep track of whether $conn is available in global scope before calling the function.

problem with "real_escape_string"

i am having some troubles my the "real_escape_string" and i need some help
login.php
<?php include('Connections/local.php'); ?>
<?php
function GetSQLValueString($sql) {
$sql = $mysqli->real_escape_string($sql);
return $sql;
}
?>
local.php
<?php
$hostname_local = "xxx";
$database_local = "xxx";
$username_local = "xxx";
$password_local = "xxx";
$mysqli = new mysqli($hostname_local, $username_local, $password_local, $database_local);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
the error is
Undefined variable: mysqli
i've tried some things ( like moving the content of the local.php inside the login.php ) but nothing works
You can't access $mysqli inside your function.
If you want to, add global $mysqli; in your function to make it accessible. Alternatively, you could pass the $mysqli as a parameter.
Why not just use the function call directly.
My suggestion, just create a simpler (and easier to read function) called "esc" and use that anytime you need to escape anything sql related.
function esc($string, $mysqli = false) {
if (!$mysqli) global $mysqli;
return mysqli_real_escape_string($mysqli,$string);
}
And then just use this by doing the following:
$sql = esc($string); //if $mysqli is already set globally, and thus will be inherited by the function
OR
$sql = esc($string,$mysqli); //if $mysqli is to be passed into each func call

Warning: Missing argument 1 for getConnection()

function getConnection($con)
{
$con = mysqli_connect('localhost', 'root', '','test') or die(mysqli_connect_error());
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "ID FROM Student";
$result = mysqli_query($con, $query);
}
Is the error caused due to $con used in the function ? Any help please.
It means you're omitting to pass an argument to the function when invoking it, i.e.
getConnection(); //<-- no arg passed
First of all, why do you use $kon as parameter and override it then?
But i would define $con to be null if no parameter is passed and if you need it.
like
function getConnection($con = null){[..]}
If possible I would remove the parameter.
If you want to create the db-connection ($con) inside your function, remove the parameter from the function declaration:
function getConnection() {
...

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
}

Categories