Making this execution work without the global pdo object
So I am trying to replace my global variables, and I am stuck to how to get pass this.
A little example of my code:
# index.php:
include "dbc.php";
echo cName(1);
# dbc.php:
try{
$connect = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset:UTF8", DB_USER, DB_PASS, $driver_options);
}
catch(PDOException $pe)
{
die('Could connect to the database because: ' .$pe->getMessage());
}
function cName($cID){
global $connect;
$sql = $connect->prepare("SELECT name FROM cocos WHERE id=:id");
$sql->bindValue(":id", $cID);
$sql->execute();
$sql = $sql->fetch();
return $sql["name"];
}
As you can see I do global $connect inside the function cName(). And so do i do to all my other functions, which looks really bad.
Can't i do anything to not have it? It says undefined function if I dont have the global variable.
I know I can add an parameter, cName($connect, 1)
But this, for me, looks as sloppy as the other. And as I have lots of functions, I would always need to include an extra parameter for this connection.
So what can I do about this, not having an extra parameter or any global vars?
I have thought maybe you could make one functi开发者_Python百科on/class/object that handles all the communications to the database, but I dont know where to start and how it should be done?
Something like:
dbQuery($query);
but then again, you cant specify bindValue() and in some cases you need to bind more than one value than in the example above.
Really hope for an solution for this, thanks in forward
Please ask in comments if questions
I will preface by saying I am at best average at php.... That being said:
class Database
{
public $dbh; // handle of the db connexion
private static $dsn = 'mysql:host=localhost;dbname=DBNAME HERE';
private static $user = 'DBUSERNAME HERE';
private static $pass = 'PASSWORD HERE';
public function factory() {
return $dbh = new PDO(self::$dsn,self::$user,self::$pass);
}
} // end of Database Class
Then In your Function, call the facotry() instance.
function cName($cID)
{
// call Database::factory, gives you access to methods and properties
$db= Database::factory();
$sql = $db->prepare("SELECT first_name FROM users WHERE id=:id");
$sql->bindValue(":id", $cID);
$sql->execute();
$sql = $sql->fetch();
// return the values
return $sql["first_name"];
} // end of cName function
You could extend the Database class if you wanted to make it more modular, easier to conifg, etc...
Hope that helps... again, I am not an expert.
What about to use a static method which return the instance of the PDO? It takes one row, same as global $connection and if you'll use multiton instead of singleton, you can choose which database you want..
精彩评论