Ok so i learning prepared statements in php because i hear they are a lot safer that mysql
So now im just getting the hand of functions. I have made a function which connects to the mysql db and have it in a different folder that the page i want to use it on. So i want all my main functions in 1 file then i want to call them from the file on the pages i need them on. But now php does not like it.
Here is my functions.php page
function mysqlconnect(){
$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = '';
$username = '';
$password = '';
// Construct the DSN, or "Data Source Name". Really, it's just a fancy name
// for a string that says what type of server we're connecting to, and how
// to connect to it. As long as the above is filled out, this line is all
// you need :)
$dsn = "mysql:host=$host;port=$port;dbname=$database";
// Connect!
$db = new PDO($dsn, $username, $password);
}
And here is my test page just testing calling the function.
include 'functions/functions.php';
mysqlconnect();
$_POST['fish'] = "shadow" ;
$statement = $db->prepare("SELECT * FROM users WHERE username = ?");
$statement->execute(array($_POST['fish']));
while ($result = $statement->fetchObject()) {
echo $result->username;
echo "<br />";
}
Notice i include the file and call the function but im getting:
Notice: Undefined variable: db
Fatal error: Call to a member function prepare() on a non-objec
If i put the connect in the same php file has it everything works fine. But of course id like all the function in the same file and just call them when ever i need them. What am i doing wrong ??
$dbis defined inside a function, so it cannot become global. It’s scope ends when the function ends.You should define
$dboutisde your function.A not-so-elegant solution:
Please take note that using
global, expecially in this context, is a really bad practice (it undermines code cleanliness, code reusability, and can lead to several other problems).A more elegant solution (like the other user says):
And then in your test page:
This is useful as you can use any variable name: makes your code more reusable in other scenarios.
would be ok too.