mysqli doesn't return instance with die() - php

I have function :
function dbConnect($usertype, $connectionType = 'mysqli') {
// some code hare
return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
}
but when I try this:
$conn = dbConnect('read');
$result = $conn->query('SELECT * FROM images');
function dosn't return anything and it say :
Fatal error: Call to a member function query() on a non-object in
C:\xampp\htdocs\phpsols\mysql\mysqli.php on line 10
but it works this way(without die())
return new mysqli($host, $user, $pwd, $db);

The [..] or die() construct leads to funny behaviour in conjunction with the return statement: The whole thing is interpreted as a boolean expression.
And because new mysqli will never be false, the "die" is never processed, and thus, your function returns true instead of a newly created instance of mysqli.
If you still would like to use or die(), do this:
$result = new mysqli($host, $user, $pwd, $db) ;
if (!$result) die ("Can't open database.");
return $result;

You can try this:
function dbConnect($usertype, $connectionType = 'mysqli') {
// some code hare
try {
return new mysqli($host, $user, $pwd, $db);
} catch(Exception $e) {
die ('Cannot open database');
}
}

aside from this funny one-liner problem, your idea of error handling is all wrong. Sadly, it was copy-pasted to other answer as well.
Here is the right code
$mysqli = new mysqli($host, $user, $pwd, $db);
if ( mysqli_connect_errno() )
{
throw new Exception(mysqli_connect_errno()." ".mysqli_connect_error());
}
return $mysqli;
Honestly, this die ('something'); thing is a childhood disease of PHP. Time to grow up a little.

Related

Pass SQL database connection to PHP function

I am calling a function from a second PHP file and I want to avoid creating the DB connection again. I am using this code but it does not work.
$Db = mysqli_init();
$Db->options(MYSQLI_OPT_LOCAL_INFILE, true);
$Db->real_connect($servername, $username, $password, $dbname, 3306);
$connection = $Db->real_connect($servername, $username, $password, $dbname, 3306);
CheckTableMetrics($connection, $dbname, $table1, $table2, $metric1, $metric2, $date1, $date2, $start_date, $end_date);
I get errors out of the blue. If I put the first part of my code in the PHP file that contains the function everything works.
The errors I get :
mysqli::query(): invalid object or resource mysqli
and
Call to a member function fetch_assoc() on a non-object
The code works fine if I just put the :
$Db = mysqli_init();
$Db->options(MYSQLI_OPT_LOCAL_INFILE, true);
$Db->real_connect($servername, $username, $password, $dbname, 3306);
Which is the best way to do it?
Your problem is fairly simple:
$connection = $Db->real_connect($servername, $username, $password, $dbname, 3306);
This is wrong. real_connect() returns a boolean marking success or failure, not a connected database object. Instead, you should send $Db into your function, and it will all work.

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.

Opening DB connection in class method

To open a DB connection, I currently use this class method :
function openDB() {
// 1. Create a database connection
$conn = mysqli_connect("x" , "x", "x","x");
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
However, I want to instead use my config file
require("assets/configs/db_config.php");
Obviously this file contains the DB connection information.
How can I do away with
$conn = mysqli_connect("x" , "x", "x","x");
And simply make $conn and make it use DB_Config.php instead?
For you config file return an array of the values you need
return array("host"=>"example.com", "dbname"=>"mydb", "username"=>"dbuser", "password"=>"secret");
Then in your openDb function do this.
function openDB() {
// 1. Create a database connection
$config = include("/path/to/config.php");
$conn = mysqli_connect($config["host"] , $config["username"], $config["password"],$config["dbname"]);
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Change
function openDB()
to
function openDB($server, $user, $pass, $dbName)
and pass those variables to mysqli_connect
and pass data from included file.I suppose, you have them in some sort of constants or defines.
Also, it would be good idea to haveDB connection somewhere globally.

PDO Error In SignUp Class

I'm working on my own SignUp class but it seems I have a problem with the PDO calls
The browser returns this to me:
Fatal error: Call to a member function query() on a non-object
I have my database configuration in a file included then on the main page. It's as follows:
<?
$dsn = 'mysql:dbname=magazin-online;host=localhost;';
$username = 'root';
$password = '';
try{
$pdo = new PDO($dsn, $username, $password);
}catch(PDOException $e){
echo 'Connection failed!: '.$e->getMessage();
}
An the line in the SignUp class causing the error is this:
$pdo->query("insert into ... () ... values ());
Now, I don't make any db connection in my SignUp class because I already included the file resposible for it.
How can I get rid of that error?
try using exec instead of query:
$pdo->exec("insert into ... () ... values ());
You are catching the exception generated by the new PDO, and then continue execution.
By doing it this way, you have to check that the class exists, so change:
if( $pdo)
$pdo->query("insert into ... () ... values ());
But .. a better way is not to continue execution after a critical error like this.
So better change the connection like this:
$dsn = 'mysql:dbname=magazin-online;host=localhost;';
$username = 'root';
$password = '';
try{
$pdo = new PDO($dsn, $username, $password);
}catch(PDOException $e){
echo 'Connection failed!: '.$e->getMessage();
die;
}
If I understand correctly, $pdo is a global variable. If you are calling $pdo->query inside a function, you either have to pass the $pdo connection as a parameter or declare it as global
global $pdo;
in the beginning of the member function.

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