Pass SQL database connection to PHP function - php

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.

Related

PHP. How can I create a functions' library?

I've got not too much experience programing but I've done a little application with a few PHP files and I'd like to optimize it.
I want to extract all the repeated code and place it inside a folder as a PHP file, that I will call later, when I need the code.
For example this lines are repeated in all my files:
$servername = "ejemplo.es";
$username = "ramon";
$dbname = "bbdd";
$password = "loquesea";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
first of all, you should read a php tutorial about functions and object orientated programming.
In your case, you could have a class for your database things called Database, which would look something like this:
<?php
class Database
{
private $_connection = null;
public function __construct($host, $username, $password, $database)
{
// connect to database and store the connection for further use
}
public function doThisAndThat()
{
// do some fancy database stuff
}
public function __destruct()
{
// important for databases is to disconnect from them
}
}
Then all you have to do is include your Database class file and call it like that:
$db = new Database($host, $username, $password, $database);
$db->doThisAndThat();

PHP Exits When I Try to Connect to a Database Using MySQLi

I have been developing a website recently, and I came across an error. When I tried to do print_r(error_get_last()); It output some text about mysql not being supported anymore, and to use MySQLi. I was all for it. When I edited my database class to support MySQLi, it exits every time it tries to connect. I have put echo 'hi<br />'; before and after the mysqli function, and a or trigger_error("Error: " . print_r(error_get_last())); at the end of it, but all it outputs is hi, and nothing else. My database is created in phpMyAdmin, and has all the correct permissions, but it just cannot connect. This is my connection code:
echo 'hi<br />';
$this->db = mysqli($host, $dbuser, $dbpass, $dbname) or trigger_error("Error: " . print_r(error_get_last()));
echo 'hi<br />';
$this->connect_start = microtime(true);
if ($this->db->connect_errno > 0) die ($this->debug(true));
It is in the constructor of a class that looks like this:
function db($host, $dbname, $dbpass, $dbuser)
and it is called like this:
$db = new db($host, $dbname, $dbpass, $dbuser);
Change this:
$this->db = mysqli()
to
$this->db = new mysqli()
mysqli is not a function, it's a class. If you had error reporting on you'd get a message like this:
PHP Fatal error: Call to undefined function mysqli()
That's the reason why the rest of your code isn't executed, the execution stops right there.
Also note that new mysqli() will never return false, so your or ... part becomes useless. If you want to check for connection errors you have to check $this->db->connect_error after the connection attempt.

Why does the 'TuckTheTorld' function not work when called from another file? [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 7 years ago.
connect_db.php:
<?php
$servername = "1.1.1.1";
$username = "root";
$password = "nope, not making this public :P";
$dbname = "seminarfach";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//$conn = new mysqli(null, $username, $password, $dbname, null, '/cloudsql/seminarfach-abi-links:data');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "<p>Connected successfully</p>";
// Set charset to UTF-8
if (!$conn->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $conn->error);
exit();
}
function TuckTheTorld() {
$conn->close();
}
?>
This is the file that connects to my database, and it is called with require "connect_db.php"; in the file that needs a connection. Now I wanted to create a function that is called to close the connection to the DB. That is the TuckTheTorld function. I named it that to make sure I don't use any keywords or overwirte any other functions.
The problem is that when I call TuckTheTorld() I get the following error:
Fatal error: Call to a member function close() on a non-object in path_to_file\connect_db.php on line 26
Why do I get that error?
You need to import the $conn object into the functions namespace by using the global keyword (there is nothing called $conn in the functions namespace because $conn resides in the global files namespace).
Just replace your function with:
function TuckTheTorld() {
global $conn;
$conn->close();
}
This should now work for you.

mysqli doesn't return instance with die()

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.

Weird PHP PDO Error

<?php
require_once('inc/dbc1.php');
$dsn = 'mysql:dbname=somedb;host=somehost';
$user = 'someuser';
$password = 'somepass';
$pdo1 = new PDO($dsn, $user, $password);
$pdo1->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth1 = $pdo1->prepare('SELECT pID, lname, fname FROM Professor ORDER BY pID DESC LIMIT 5;');
$sth1->execute(array());
?>
Fatal error: Class 'PDO' not found on line 7
Line 7 is: $pdo1 = new PDO($dsn, $user, $password);
Why does this give this error and how do I fix it? All I'm trying to do is connect with the credentials and run that query
$pdo1 = new PDO($dsn, $user, $password);
PHP is looking for the class PDO on this line, I'm assuming it is in the file you included. Check to make sure it's the right file. PHP can't find the class definition. Maybe, make sure it is spelled correctly too.
If you're using a newer PHP version, you might have to prefix global classes with the global namespace identifier: "\"
So it would become: $pdo1 = new \Pdo(...);

Categories