Reputation: 23
I get these errors after trying to make my code more secure:
Notice: Undefined variable: db in .../init.php on line 10
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in .../init.php on line 10
Notice: Undefined variable: db in .../init.php on line 10
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in .../init.php on line 10
And this is the code I use:
require 'database/connection.php';
error_reporting(E_ALL);
ini_set('display_errors',1);
session_start();
function makeSafe($safe)
{
$safe = mysqli_real_escape_string($db, $safe);
return $safe;
}
The $db variable is defined in connection.php so it should work right? And for some reason it's doesn't recognize the mysqli I use in connection.php
$host = '...';
$username = '...';
$password = '...';
$dbnaam = '...';
$db_error1 = '...';
$db_error2 = '...';
// Verbinden met Databaseserver
$db=mysqli_connect($host, $username, $password, $dbnaam) or die($db_error1);
// Verbinden met Database
mysqli_select_db($db, $dbnaam) or die($db_error2);
And this has always worked just fine for me. So I don't understand what I'm doing wrong here. Any help is very much appreciated.
Upvotes: 0
Views: 333
Reputation: 2128
function makeSafe($safe)
{
global $db;
$safe = mysqli_real_escape_string($db, $safe);
return $safe;
}
or
function makeSafe($db,$safe)
{
$safe = mysqli_real_escape_string($db, $safe);
return $safe;
}
Upvotes: 1
Reputation: 18861
A good approach might be like this:
External file
<?php
$host = '...';
$username = '...';
$password = '...';
$dbnaam = '...';
$db_error1 = '...';
$db_error2 = '...';
// Verbinden met Databaseserver
$db=mysqli_connect($host, $username, $password, $dbnaam) or die($db_error1);
// Verbinden met Database
mysqli_select_db($db, $dbnaam) or die($db_error2);
return $db;
Main file:
<?php
$db = require('database/connection.php');
... the rest of the code ...
Note that to use $db in the function, you must use the global
keyword.
Upvotes: 0
Reputation: 666
Variable scope problem. Try this:
function makeSafe($safe)
{
global $db;
$safe = mysqli_real_escape_string($db, $safe);
return $safe;
}
Upvotes: 1