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();
Related
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().
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
I am at learning stage of PHP. I am using a php file to process form data for sql table and it has server name, user, password and dbname to perform sql-connect query. And of course it is in public directory of website. Is it a safe way or any suggestion is appreciated. example is as follow:
$name = $_POST['name'];
$phn = $_POST['phn'] ;
$servername = "localhost";
$username = "abc";
$password = "abc";
$dbname = "abc";
// Create connection
$conn = mysqli($servername, $username, $password, $dbname);
Connecting using the mysqli extension gives you the ability to use newer MySQL features such as transactional queries and parameterised queries which aren't available using the older mysql extension.
Have a look at MySQL Improved Extension # php.net
Your mysql should be mysqli_connect ()
You forgot new before instantiating the MySQLi connection.
Try this instead:
$conn = new mysqli($servername, $username, $password, $dbname);
You can store database credentials anywhere, but better store them somewhere OUTSIDE of your main PHP folder, using this approach:
/config/db.config.php
<?php
define('DB_USER', 'root');
define('DB_PASS', 'pass');
define('DB_DATABASE', 'database');
define('DB_HOST', 'host');
If you will store it INSIDE of your php folder, each time, when you copy your code from local to web, you will override your configurations. Also, such file is safe (if you will accss it from web, you will see nothing), but I stil advice to put here .htaccess file with deny for all content.
Also, I can advice DO NOT USE mysqli_connect without any wrapper. (better use PDO with parametrised queries). But, if you want to work with mysqli, better search in web for good wrapper, or write it by self. From my experience, most better way to work with mysqli is create class with static functions:
class DB {
public static function init($dbHost, $dbUser, $dbPass, $db);
public static function getTable($query);//get array of arrays
public static function getRow($query);//get array (one database row)
public static function getCell($query);//get single value
public static function getColumn($query);//get array (column)
public static function query($query);//update, delete, insert
}
because with this class you will be able to get data in any place of your script using something:
$list = DB::getTable("select * from table");
please try this
<?php
$servername = "localhost";
$username = "abc";
$password = "abc";
$dbname = "abc";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$name = $_POST['name'];
$phn = $_POST['phn'] ;
?>
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.
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.