How to connect to MySQL using PDO using PHP function [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm using this method to connect to my MySQL db to SELECT, INSERT, UPDATE and DELETE data. This is the cnn() function:
function cnn() {
static $pdo;
if(!isset($pdo)) {
$settings = [
PDO::ATTR_TIMEOUT => 30,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
try {
# settings
$config['db']['host'] = 'example.com';
$config['db']['name'] = 'db';
$config['db']['user'] = 'username';
$config['db']['pass'] = '****************';
$pdo = new PDO('mysql:host='.$config['db']['host'].';dbname='.$config['db']['name'], $config['db']['user'], $config['db']['pass'], $settings);
return $pdo;
} catch(PDOException $e) {
http_response_code(503);
echo $e->getCode().': '.$e->getMessage();
}
} else {
return $pdo;
}
}
And then i can just do this to re-use the same pdo object each time i need it on the same request.
1st query
$sql = 'INSERT INTO user (name, lastname) VALUES (:name, :lastname)';
$stmt = cnn()->prepare($sql);
$stmt->bindValue(':name', "John", PDO::PARAM_STR);
$stmt->bindValue(':name', "Wayne", PDO::PARAM_STR);
$stmt->execute();
2nd query
$sql = 'SELECT * FROM user WHERE id_user = :id_user';
$stmt = cnn()->prepare($sql);
$stmt->bindValue(':id_user', 4641, PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch();
I was wondering if there could be any performance issues by using this approach. Thanks.

1)
As referenced by HTMHell, your $config array is local here and I believe this should be deleted after use so password variables are not leakable on a later get_defined_vars() call, or similar cross reference.
2)
It seems far more logical to me to put your function in a class. Run the cnn() function from the __construct. There are a lot of positive aspects to wrapping this function in a full class.
3)
Do NOT set any variable to being static unless you have a specific requirement in the context of putting your cnn() function into a Class.
4)
Correctly use your try{ ... } catch { ... } blocks, do not wrap other code in the try block except code that throws exceptions.
// settings
$config['db']['host'] = 'example.com';
$config['db']['name'] = 'db';
$config['db']['user'] = 'username';
$config['db']['pass'] = '****************';
try {
$pdo = new PDO('mysql:host='.$config['db']['host'].';dbname='.$config['db']['name'], $config['db']['user'], $config['db']['pass'], $settings);
} catch(PDOException $e) {
/***
* Do you really need this, here?
* //http_response_code(503);
**/
echo $e->getCode().': '.$e->getMessage();
}
return $pdo;
5)
DO NOT EVER OUTPUT ERRORS DIRECTLY TO THE SCREEN
Errors should be logged so only server folks and developers rather than the general public can see them. This also means you have a log of errors rather than a single, temporary instance of any that occur.
echo $e->getCode().': '.$e->getMessage(); Should be:
error_log($e->getCode().': '.$e->getMessage());
Or similar. Stay consistent; always return a PDO object and not echo outputs.
6)
Remove your final else wrapper it is merely clutter.
if(!isset($pdo)) {
...
}
return $pdo;
Also remove the return $pdo; inside your try { ... } block. Don't Repeat Yourself.
7)
Properly document your code:
/***
* For generating or asserting a PDO Database Object.
* #return Returns the PDO object
***/
function cnn() {
To answer the question you actually asked:
I was wondering if there could be any performance issues by using this approach.
This question is far too broad and can be solved by yourself using timer testings or other methods (detailed in the link) to establish on your system if it is particularly efficient or inefficient, or what SQL you choose to give it...

Related

A template code to execute stored procedures

Usually when it is necessary to communicate with MySQL via PHP I use a template similar to the one below (which is similar to the ones available in beginners tutorials):
// Exception Handler
class customException extends Exception {}
// Database Link (include file in a private directory)
function db_connect()
{
$hostname = "localhost";
$username = "username";
$password = "password";
$database = "database";
$connection = mysqli_connect($hostname, $username, $password, $database);
return $connection;
}
// Template for calling common types of stored procedures:
// select a table row based on the primary key (pk)
function select_pk($connection, string $pk): array
{
// if other database is needed
mysqli_select_db($connection, "database1");
// query execution
$query = sprintf("CALL select__pk('%s')", mysqli_real_escape_string($connection, $pk));
$resource = mysqli_query($connection, $query);
$result = mysqli_fetch_assoc($resource);
// prepare for next query
mysqli_free_result($resource);
while(mysqli_more_results($connection)) mysqli_next_result($connection);
// use exception handling if necessary
if(!isset($result)) throw new customException('pk not found');
return $result;
}
// Typical execution
$connection = db_connect();
try
{
$result = select_pk($connection, $pk);
}
catch(customException $e)
{
/*** do something ***/
}
Although this template is, so far, working fine (single server), I have the impression that:
the preparation for next query is overcomplicated (mysqli_free_result, mysqli_more_results and mysqli_next_result)
it does not deal properly with errors
Question
Any comments or advice on how to improve this template?
Well, first I would give a generalized answer that likely would help other people stumbling upon this question and then review the particular case of yours.
I asked myself exactly the same question a long time ago and eventually came to a set of solutions that ease the database operations using mysqli.
Mysqli connection
I have doubts about storing a connection code in a function. It asks to be misused. A connection to a single database should be established strictly once during a single HTTP request/php instance. but a function's purpose to be called multiple times. It would be better to put the connection code in a file instead, and then just include this file in your code in a single place.
I've got a canonical mysqli connection code that deals with a whole lot of problems before they even appear. So, instead of function db_connect() let's create a file called mysqli.php and put the following code there
<?php
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$conn = new mysqli($host, $user, $pass, $db);
$conn->set_charset($charset);
} catch (\mysqli_sql_exception $e) {
throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}
unset($host, $db, $user, $pass, $charset); // we don't need them anymore
Among other solutions it will translate mysql errors into PHP exceptions which is, basically all you need in order to deal with errors.
Running prepared queries
The next problem is rather elaborate code required for the prepared queries in mysqli. To deal with it i wrote a mysqli helper function that eases the process dramatically.
note that although your current approach with mysqli_real_escape_string() is technically safe, it is frowned upon never the less, as it's a subject of human errors of all sorts. Better stick to prepared statements for all queries that involve a PHP variable as input.
So next solution would be a helper function like this
function prepared_query($mysqli, $sql, $params = [], $types = "")
{
if (!$params) {
return $mysqli->query($sql);
}
$types = $types ?: str_repeat("s", count($params));
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt->get_result();
}
and you will get a tool that will make prepared statements as smooth as regular queries
Calling stored procedures with mysqli
Stored procedures are not easy because of a quirk: every call returns more than one resultset and therefore we need to loop over them. We cannot avoid it but at least we can automatize this process too. We can write a function that encapsulates all the resultset jiggery-pokery.
function prepared_call($mysqli, $sql, $params = [], $types = ""): array
{
$resource = prepared_query($mysqli, $sql, $params, $types);
$data = $resource->fetch_all(MYSQLI_ASSOC);
while(mysqli_more_results($mysqli)) mysqli_next_result($mysqli);
return $data;
}
A specifik function to call for a PK
And finally we can rewrite your select_pk() function
function select_pk($mysqli, string $pk): array
{
$data = prepared_call($mysqli, "CALL select__pk(?)", $pk);
return $data[0] ?? null;
}
I am not really sure we need an exception here though:
include 'mysqli.php';
$result = select_pk($mysqli, $pk);
if (!$result) {
/*** do something ***/
}

Error SQL Syntax

hi im rather new to SQL and im currently trying to save some data into a Sql database using a website. But everytime i run it i get some Syntax error and now after many hours of looking i was hoping somebody in here knew an answer, or could lead me in the right direction :)
this is the error i get when i hit my submit button :
0You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[Campus one],[101],[2016-12-08],[test])' at line 1
this is the insert part of the script, connection part seems to be running fine
$sql = "INSERT INTO `formel`(`Område`, `Værelse`, `Dato`, `TV Fjernsyn Forlænger`) VALUES ([$area],[$filnavn],[$dato],[$Fjernsyn]) ";
SQL information:
Your values need to be changed from:
[$area],[$filnavn],[$dato],[$Fjernsyn]
to:
'{$area}','{$filnavn}','{$dato}','{$Fjernsyn}'
You should really be binding your params though. I assume you're using mysql_ which you shouldn't be using anymore therefore I also suggest you look into mysqli_ or PDO.
Edit:
You should move over to PDO in fairness, I did and I love it!
I work with classes a lot as it's a neater way to work so I'll give you my input:
Make yourself a dbConfig.php file:
class Database
{
private $host = "localhost";
private $db_name = "dbName";
private $username = "username";
private $password = "password";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
So because i am half lazy and why type code over and over?
Create yourself a dbCommon.php file.
class DBCommon
{
private $conn;
/** #var Common */
public $common;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
Then you need a class file for your PDO to go into such as:
class.update.php:
require_once('dbCommon.php');
class Update extends DBCommon
{
function __construct()
{
parent::__construct();
}
public function updateCode($area, $filnavn, $dato, $Fjernsyn)
{
$stmt = $this->runQuery("INSERT INTO `formel` (`Område`, `Værelse`, `Dato`, `TV Fjernsyn Forlænger`) VALUES (:area, :filnavn, :dato, :Fjernsyn)");
$stmt->bindParam(array(':area' => $area, ':filnavn' => $filnavn, ':dato' => $dato, ':Fjernsyn' => $Fjernsyn));
$stmt->execute();
echo "Your insert command has been completed!";
}
}
Then within your file.php where you would be calling the class you need to do:
require_once ('class.update.php');
$update = new Update();
if (isset($_POST['send']))
{
$update->updateCode($_POST['area'], $_POST['filnavn'], $_POST['dato'], $_POST['Fjernsyn']);
}
Note: Because you didn't post your $_POST['name']'s in I have given you a base example.
Binding your params is best practice as this prevents SQL Injection.
With binding params you dont have to run $stmt->bindParam(); You can simply run $stmt->execute(array(':paramshere' => $paramVar));
It totally depends on your preference but I always prefer binding before executing (personal preference). I hope this gives you some input and insight on how to move into PDO instead but it really is the way forward.
In order to prevent SQL injection, you should really use Prepared Statements, or correctly escape your strings. Please look at MySQLi or PDO.
Here's a basic tutorial using PDO and Prepared Statements inside of PHP:
// Connect to the database:
$db = new PDO( 'mysql:dbname=DB_NAME;host=localhost', 'DB_USER', 'DB_PASS' );
// Prepare the statement:
$ins = $db->prepare( 'INSERT INTO `formel` (`Område`, `Værelse`, `Dato`, `TV Fjernsyn Forlænger`) VALUES (:area, :filnavn, :dato, :Fjernsyn' );
// Execute with bindings:
$ins->execute(array(
':area' => $area,
':filnavn' => $filnavn,
':dato' => $dato,
':Fjernsyn' => $Fjernsyn
));
Try This,
$sql = "INSERT INTO `formel`(`Område`, `Værelse`, `Dato`, `TV Fjernsyn Forlænger`) VALUES ('$area','$filnavn','$dato','$Fjernsyn') ";
I think it should work.
Change your query to this
$sql = "INSERT INTO formel(Område, Værelse, Dato, TV Fjernsyn Forlænger) VALUES ('$area','$filnavn', '$dato', '$Fjernsyn') ";
But I would suggest you use prepared statement for security purposes

Creating a PHP PDO database class, trouble with the OOP

this is my current Database class:
class Database {
private $db;
function Connect() {
$db_host = "localhost";
$db_name = "database1";
$db_user = "root";
$db_pass = "root";
try {
$this->db = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_pass);
} catch(PDOException $e) {
die($e);
}
}
public function getColumn($tableName, $unknownColumnName, $columnOneName, $columnOneValue, $columnTwoName = "1", $columnTwoValue = "1") {
$stmt = $this->db->query("SELECT $tableName FROM $unknownColumnName WHERE $columnOneName='$columnOneValue' AND $columnTwoName='$columnTwoValue'");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results[0][$unknownColumnName];
}
}
I'm trying to run it using the following code:
$db = new Database();
$db->Connect();
echo $db->getColumn("Sessions", "token", "uid", 1);
And i get the following error:
PHP Fatal error: Call to a member function fetchAll() on a non-object in /Users/RETRACTED/RETRACTED/root/includes/Database.php on line 19
Any idea what's up? Thanks
This function is prone to SQL injection.
This function won't let you get a column using even simplest OR condition.
This function makes unreadable gibberish out of almost natural English of SQL language.
Look, you even spoiled yourself writing this very function. How do you suppose it to be used for the every day coding? As a matter of fact, this function makes your experience harder than with raw PDO - you have to learn all the new syntax, numerous exceptions and last-minute corrections.
Please, turn back to raw PDO!
Let me show you the right way
public function getColumn($sql, $params)
{
$stmt = $this->db->prepare($sql);
$stmt->execute($params);
return $stmt->fetchColumn();
}
used like this
echo $db->getColumn("SELECT token FROM Sessions WHERE uid = ?", array(1));
This way you'll be able to use the full power of SQL not limited to a silly subset, as well as security of prepared statements, yet keep your code comprehensible.
While calling it still in one line - which was your initial (and extremely proper!) intention.
it means your $stmt variable is not returning a PDOStatement object. your query is failing since PDO::query either returns a PDOStatement or False on error.
Use fetch instead of fetchAll..that will be easy in your case
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results[0][$unknownColumnName];
It will be
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results[$unknownColumnName];

PHP function to open database using PDO

I realize this is probably super simple but i just started taking peoples advice and im converting a small program from mysql to PDO as an attempt to learn and switch to PDO.
The script is a script that shows you how to build a shopping cart, so keep in mind its focused on a learning audience like myself. Anyway i converted the old script here:
function db_connect()
{
$connection = mysql_pconnect('localhost', 'database_1', 'password');
if(!$connection)
{
return false;
}
if(!mysql_select_db('database_1'))
{
return false;
}
return $connection;
}
to this which does connect fine:
function db_connect() {
//Hostname
$hostname = 'xxx.com';
//username
$username = 'xxx';
//password
$password = 'xxx';
try {
$connection = new PDO("mysql:host=$hostname;dbname=database_1", $username, $password);
}
catch(PDOException $e){
echo $e->getMessage();
}
}
Now in other parts of the script before accessing the database it does this:
$connection = db_connect();
Now i have 2 questions. First is to help me understand better what is going on.
I understand in the original mysql function we connect to the database, if the connection is unsuccessful or the database doesnt exist it returns false. If it does connect to the database then it returns true.
With that i mind i dont understand this:
$connection = db_connect();
Isnt that just assigning true or false to the $connection variable, if so then whats going on in this part of the code.
$price = 0.00;
$connection = db_connect();
if (is_array($cart))
{
foreach($cart as $id => $qty)
{
$query = "SELECT price
FROM products
WHERE products.id = '$id' ";
$result = mysql_query($query);
if($result)
{
$item_price = mysql_result($result, 0, 'price');
$price += $item_price * $qty;
}
}
}
Instead couldn't i just create an include file with the PDO connection and no function and include that at the top of each page i run scripts on. I just don't understand where the $connection = db_connect comes in.
So the 2nd question if my above suggestion is not the answer is how do i return a boolean value from the connection function to return true or false (If i even need to)
There is one essential difference between old mysql and PDO: both these libraries require a resource variable to connect with. If you take a look at mysql_query() function definition, you will notice the second parameter, represents such a resource.
$connection variable returned by your old function by no means contain boolean value but such a resource variable. Which can be used in every mysql_query call.
But while for mysql ext this resource parameter being optional, and used automatically when not set, with PDO you have to address this resource variable explicitly. Means you cannot just call any PDO function anywhere in the code, but only as a method of existing PDO object. Means you have to make this variable available wherever you need PDO.
Thus, you need not a boolean but PDO object.
Here is the right code for the function:
function db_connect()
{
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
return new PDO($dsn,'root','', $opt);
}
now you can use it this way
$pdo = db_connect();
but note again - unlike with mysql_query(), you have to always use this $pdo variable for your queries.
Further reading is PDO tag wiki
As you guessed from the context, db_connect() is supposed to return the connection object. Your converted version doesn't return anything, which is a problem.
With the mysql module, you can run queries without using the connection object - this is not the case with PDO. You'll need to use the connection object to run any queries -
$result = $connection->query('SELECT * FROM foo');
First off, let me congratulate you for making the effort to learn PDO over mysql_*. You're ahead of the curve!
Now, a few things to understand:
PDO is OO, meaning the connection to the database is represented by a PDO Object.
Your db_connect() function should return the object that gets created.
Passing in the parameters required by PDO will give you more flexibility!
So what we have is:
function db_connect($dsn, $username, $password)
{
$conn = new PDO($dsn, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //This makes sure that PDO will throw PDOException objects on errors, which makes it much easier enter code hereto debug.
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //This disables emulated prepared statements by PHP, and switches to *true* prepared statements in MySQL.
return $conn; //Returns the connection object so that it may be used from the outside.
}
Now, you may have noticed we aren't checking for PDOExceptions inside of the function! That's because you can't handle the error from inside of the function correctly (becuase you don't know what you would want to do? Would you terminate the page? Redirect to an error message?). So you can only know it when you call the function.
So usage:
try {
$connection = db_connect("mysql:host=$hostname;dbname=database", "user", "pass");
}
catch (PDOException $e) {
echo "Database error! " . $e->getMessage();
}
Further Reading!
The PDO Manual entry - is super easy and super useful. I recommend you read all of it.

Do I have this PDO Connection Class right?

I've been playing around with PDO for the last few days, I'm working on a small CMS system to teach myself OOP skills, but even though it's only a small CMS, I want it to be able to handle whatever the web can throw at it.
This is what I've come up with so far, I'm going to add connection pooling to the constructor to enable large amounts of concurrent connects on demand. I'm very new to this OOP stuff so I'm wanting a little advise and critism, no doubt I've done something terribly wrong here.
I took the top answer to Global or Singleton for database connection? as the base design, although I've added a private constructor as I want to use $this->dbConnectionInstance throughout the class for numerous helper functions to use.
Thanks very much for your time, I really will appreciate any advise you can give me,
-Drew
// Usage Example: $dbconn = dbManager::getConnection();
// $dbconn->query("SELECT * FROM accounts WHERE id=:id", "':id' => $id");
<?php
class dbManager {
private static $dbManagerInstance;
private $dbConnectionInstance;
private $stime;
private $etime;
public $timespent;
public $numqueries;
public $queries = array();
public static function getManager(){
if (!self::$dbManagerInstance){
self::$dbManagerInstance = new dbManager();
}
return self::$dbManagerInstance;
}
// Server details stored in definition file
private function __construct($db_server=DB_SERVER, $db_user=DB_USER, $db_pass=DB_PASS, $db_params=array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")) {
if(!$this->dbConnectionInstance)
{
try{
$this->dbConnectionInstance = new PDO($db_server, $db_user, $db_pass, $db_params);
$this->dbConnectionInstance->setAttribute(PDO::ATTR_PERSISTENT, PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$this->dbConnectionInstance = null;
die($e->getMessage());
}
}
return $this->dbConnectionInstance;
}
private function __destruct(){
$this->dbConnectionInstance = null;
}
private function query($sql, $params = array()) {
$this->queries[] = $sql;
$this->numqueries++;
$this->sTime = microtime();
$stmt = $this->dbConnectionInstance->prepare($sql);
$stmt->execute($params);
$this->eTime = microtime();
$this->timespent += round($this->eTime - $this->sTime, 4);
return $stmt;
}
}
?>
Thank you both for your suggestions, I've now added the rollback and commit into my exception handling, I'm just researching the use of buffered queries, I'm not entirely sure what ths will give me?
Looks good, I would add rollback functionality, along with the buffered query/errorInfo suggestions (If you're using a RDBMS that supports transactions):
try {
$this->dbConnectionInstance->beginTransaction();
$stmt = $this->dbConnectionInstance->prepare($sql);
$stmt->execute($params);
$this->dbConnectionInstance->commit();
}catch(PDOException $e){
$this->dbConnectionInstance->rollback();
}
commit() , beginTransaction()
EDIT: added links below for more info on buffered queries:
mysql performance blog
pdo mysql buffered query support
stack overflow: pdo buffered query problem
The code you have dosent look too bad. however if i could make a couple small changes (mainly error handling).
both the prepare and execute statements will return false on error. and you can access the error from $this->dbConnectionInstance->errorInfo() in your example above.
also if you plan on using any large queries I suggest using a buffered query: PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
looks like a good start. Good luck on your CMS.

Categories