PHP Pass variables between PHP files - php

I have a DB connection in a connection.php file.
With
"require_once"
I include the connection function in a second .php file.
In this second .php file I call another function from an another .php file and I would like to pass the connecction variable to this function.
In main file.php i have this:
require_once("connection.php");
require_once("print.php");
DBconnection(); //Standard connection to a DB
print("connection");
In connection.php i have:
function DBconnection()
{
$connection= new mysqli($host, $user, $password, $database);
if ($connection->connect_errno)
{
echo "$connection->connect_error . ".";
exit();
}
}
Can I pass the connection variable from connection.php to print("connection")?
print("connection") is a function that print something from the DB choosen from connection.php

So you need to create a function, which you have but below is an example:
function functionName($your, $variables, $here)
{
//code
}
Then you would pass variables into it like so...
functionName($your, $variables, $here);

Your function isn't returning a value, so if you want to pass that object back to the calling code, you just need to return it:
function DBconnection()
{
$connection = new mysqli($host, $user, $password, $database);
if ($connection->connect_errno) {
echo $connection->connect_error . " . ";
exit;
}
return $connection;
}
Then, just store the function result to a variable so you can use it later:
require_once("connection.php");
require_once("print.php");
$db = DBconnection(); //Standard connection to a DB

Related

Correct way of having multiple php functions to query a single (mysql) database

Working on a PHP website and I've encountered an efficiency issue that I can not solve on my own.
I have a couple of separate php files:
connection.php - connects to the database.
sqlFunctions.php - couple of functions that execute different sql (mysqli) queries, manipulate data and return it.
index.php - file that executes some of the functions from sqlFunctions.php and uses the returned values to display something in the page.
connection.php:
$servername = "DATA"; //Replaced to "DATA" for posting on stackoverflow
$username = "DATA";
$password = "DATA";
$dbname = "DATA";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
sqlFunctions.php:
<?php
function query1(){
require('connection.php');
//PDO Query to DB, fetch, store, modify data etc.
mysqli_close($con);
//Return modified data
}
function query2(){
require('connection.php');
//PDO Query to DB, fetch, store, modify some other data etc.
mysqli_close($con);
//Return modified data
}
?>
index.php:
//Simplified version
require('sqlFunctions.php');
<?php echo query1();?>
So I was thinking - initiating a new connection to the db on every function call is not a good idea. And if I would initiate a connection to the db in a function in sqlFunctions.php - I would need to pass another variable/reference/pointer (you know what I mean) to every single function in that file and that is something that I don't want to do.
So what is the best approach to accomplish what I need?
TL;DR;:
Main file calls a function in a separate file
That function executes an sql query and returns data
Returned data is displayed
Without reopening/closing the db connection on every function call.
There are several options.
Option 1. Declare your database connection global inside each function.
sqlFunctions.php:
<?php
require('connection.php');
function query1(){
global $con;
// mysqli code with $con
}
function query2(){
global $con;
// mysqli code with $con
}
?>
Option 2. Use GLOBALS.
connection.php:
...
$GLOBALS['con'] = new mysqli($servername, $username, $password, $dbname);
...
sqlFunctions.php:
<?php
require('connection.php');
function query1(){
// mysqli code with $GLOBALS['con']
}
function query2(){
// mysqli code with $GLOBALS['con']
}
?>
Option 3. Wrap all functions into a class (note capital S).
SqlFunctions.php:
class SqlFunctions {
protected $con;
public function __construct() {
global $con;
// can also pass $con as parameter or init db here
$this->con = $con;
}
public function query1(){
// mysqli code with $this->con
}
public function query2(){
// mysqli code with $this->con
}
}
index.php:
require('SqlFunctions.php');
$sqlFunctions = new SqlFunctions();
<?php echo $sqlFunctions->query1();?>
In this case you can also initialize the connection right inside the class or pass it as a parameter to __construct().

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();

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.

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

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.

Categories