How can I avoid using global to access a variable inside a php function. I know I can store them as constants, but my variables contain sql and are many. Like this...
$selectSql = 'select name from table where name = :thisName' and year = :thisYear;
$selectSqlBind = array(":thisName" => $thisName,":thisYear" => $thisYear);
Here's how I currently do it
function myFunction (){
global $selectSql;
global $selectSqlBind;
$addUser = $conn->prepare($selectSql);
$addUser->execute($selectSqlBind);
//Other Stuff goes on
}
I also can do
function myFunction ($selectSql,$selectSqlBind){
$addUser = $conn->prepare($selectSql);
$addUser->execute($selectSqlBind);
//Other Stuff goes on
}
but how can I do
function myFunction (){
$addUser = $conn->prepare($selectSql);
$addUser->execute($selectSqlBind);
//Other Stuff goes on
}
-
1What restrains you from using parameters ?HamZa– HamZa2013年06月17日 08:43:09 +00:00Commented Jun 17, 2013 at 8:43
-
1You're probably looking for a class, it solves exactly this kind of problem.deceze– deceze ♦2013年06月17日 08:45:39 +00:00Commented Jun 17, 2013 at 8:45
2 Answers 2
This is what you'd use a class for. You could for example easily just extend the MySQLi class, keep all the functionality, but add your own functions. Then you'd simple refer to the MySQLi statements by $this instead of $conn:
<?php
class DB extends mysqli {
const PASSWORD_SALT = "abc123";
public function AddUser($username, $password) {
$addUser = $this->prepare("INSERT INTO `users` (`username`, `password`) VALUES (:username, :password)");
$addUser->execute(array(":username" => $username, ":password" => md5(self::PASSWORD_SALT . $password)));
}
}
?>
If you'd prefer to keep the two logics seperate, this is also very possible.
You'd refer to the DB by the class variable $conn refered to (from the class itself) as $this->conn. If you want to use this variable outside the class, you'd have to turn private $conn into public $conn and then you could refer to it by using $db = new DB(); $db->conn->prepare(/*etc*/);:
<?php
class DB {
const PASSWORD_SALT = "abc123";
private $conn;
public function __construct() {
$this->conn = new mysqli("localhost", "foo", "bar", "foobar");
}
public function AddUser($username, $password) {
$addUser = $this->conn->prepare("INSERT INTO `users` (`username`, `password`) VALUES (:username, :password)");
$addUser->execute(array(":username" => $username, ":password" => md5(self::PASSWORD_SALT . $password)));
}
}
?>
Comments
You should be using function parameters for this, so pass the query and the bind parameters along.
The database connection itself however should be obtained by some other method. Either take a good look at some PHP frameworks and how they solve this issue, or read up on design patterns like Singleton, Registry Pattern or Dependency Injection Container, etc.