problem with "real_escape_string" - php

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

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 Pass variables between PHP files

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

Cannot call MySQL when including class in PHP

I've got a problem with include. I'm doing some kind of blog, and at this moment it looks like this:
index.php
article.php
class/art.class.php
Let's focus on article.php, which looks like this:
<?php
$mysqli = new mysqli("","","",""); // here are my connection details
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$mysqli->query("SET NAMES 'utf8'");
require("class/art.class.php");
$art = new Article();
print_r($art->get_art(trim($_GET['id'])));
$mysqli->close();
?>
And art.class.php is like this:
<?php
class Article {
function get_art($id) {
if(!is_numeric($id)) {
header("Location: index.php");
die("<h2>ID isn't numeric, cannot go on.</h2>'");
}
if($result = $mysqli->query("SELECT * FROM `articles` WHERE id='$id';")) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$art = $row;
}
$result->close();
}
return $art;
}
}
?>
The problem is a response from MySQL. Sorry, I mean no response. And no errors. I figured out that I need to add mysql connection code to class code. But why? How I can connect once to database and call it from anywhere, even from included class?
And sorry if my english is bad..
The get_art function within the Article class does not have access to variables outside of it's scope: please see the answer here.
In order to fix your issue, you may provide access to the $mysqli object by passing it to the constructor of the Article class when you instantiate it:
Article.php:
$mysqli = new mysqli("","","",""); // your connection details
$art = new Article($mysqli);
art.class.php:
class Article {
protected $mysqli;
public function __construct($mysqli) {
$this->$mysqli = $mysqli;
}
function get_art($id) {
// Replace $mysqli with $this->mysqli everywhere you need to
// make database calls
}
}
Although some would recommend that you avoid doing so, you could use PHP's $GLOBALS variable to store your database connection:
$mysqli = new mysqli("","","",""); // here are my connection details
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$GLOBALS['mysql'] = $mysqli;
This way you would have access to it within your class:
class Article
{
function get_art($id)
{
$mysqli = $GLOBALS['mysqli'];
...
}
}

Cant pass mysqli connection to class

I am trying to pass an mysqli database connection to a php class. The code I have so far (cut down for simplicity) is as follows:
db.php
$db_host = 'localhost';
$db_name = 'dbname';
$db_user = 'username';
$db_password = 'password';
$db = array('db_host'=>$db_host,
'db_name'=>$db_name,
'db_user'=>$db_user,
'db_password'=>$db_password);
$dbCon = new mysqli( $db['db_host'],
$db['db_user'],
$db['db_password'],
$db['db_name']);
if (mysqli_connect_errno())
{
die(mysqli_connect_error()); //There was an error. Print it out and die
}
index.php
<?php
require_once($_SERVER["DOCUMENT_ROOT"] . "/db.php");
$sql = "SELECT id FROM usr_clients";
$stmt = $dbCon->prepare( $sql );
if ($stmt)
{
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch())
{
$cl = new Client($id, $dbCon);
$cl->doIt();
}
$stmt->close();
}
?>
client.php
<?php
Class Client
{
private $con;
public static $clientCount = 0;
public function __construct( $id, $con )
{
$this->con = $con;
$sql = "SELECT id FROM usr_clients WHERE id = $id";
$stmt = $this->con->prepare( $sql );
if ($stmt)
{
echo "it worked!";
}
else
{
echo "it failed";
}
}
}
?>
Now the index.php page successfully recognises the database connection declared in db.php, and returns a list of all clients. It then loops through each client, and creates a "client" object, passing it the database connection.
It is here that the problem seems to start. In the client class, the database connection is not recognised. I get multiple errors on the page saying "it failed". In the logs, there is a line about calling prepare() on a non object.
Can anyone explain why the connection works in index.php, but not in the client class?
Thanks
Your main problem is assumptions.
You are assuming that there is no connection passed, judging by indirect consequence.
But a programmer should be always logically correct in their reasoning.
Talking of connection? Verify the very connection. var_dump($con) in the constructor. var_dump($this->con) in the method. If it fails - only now you can blame connection and start for the solution.
If not - there is no reason in looking for another connection passing method. Yet it's time to find the real problem.
If your query fails, you have to ask mysql, what's going on, using $this->con->error, as this function will provide you with a lot more useful information than simple "it fails". The right usage I've explained here: https://stackoverflow.com/a/15447204/285587

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