This question already has an answer here:
Something doesn't work in my PHP code. The function mysqli_query()
inside the function db_query()
has no access to the previously defined variable link
. Why?
<?php
$link = mysqli_connect($hostname, $username, $password,$database);
function db_query($sql) {
return mysqli_query($link ,$sql);
}
db_query('SELECT name FROM users LIMIT 1');
My problem is that I always get this Error:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ...
</div>
For people looking at this question in the future:
In PHP, you do not have access to variales outside of the function like you can see above.
Go to variable scope to learn more.
There are a lot of solutions for this problem, but I prefer one that I show you here (including PDO). If you create a class and initialize your connection when a new object of this instance is made, it will be very easy to query sql later.
<?php
class Users {
private $_conn;
public function __construct() {
//initialize the connection
$this->_conn = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8', USERNAME, PASSWORD);
}
public function __destruct() {
//close the connection when the database connection is not needed anymore
$this->_conn = null;
}
public function do_something() {
$this->_conn->query("SELECT name FROM users LIMIT 1");
}
}
$users = new Users(); //initialize the new object Users
$users->do_something();
This is a scope issue.
Must be function db_query($db_conn,$sql) {
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$query = "SELECT name FROM mytable");
$result = mysqli_query($link, $query);
I hope this works