I just started switching my project form the mysql to PDO. In my project a new PDO Object is created more or less right a the beginning of the programm.
$dbh_pdo = new PDO("mysql:host=$db_url;dbname=$db_database_name", $db_user, $db_password);
Now I would like to use this handler (is that the correct name?) in some functions and classes. Is there a way to make objects global just like variables or am I trying something unspeakably stupid, because I couldn't find anything when searching the web ...
Yes, you can make objects global just like any other variable:
$pdo = new PDO('something');
function foo() {
global $pdo;
$pdo->prepare('...');
}
You may also want to check out the Singleton pattern, which basically is a global, OO-style.
That being said, I'd recommend you not to use globals. They can be a pain when debugging and testing, because it's hard to tell who modified/used/accessed it because everything can. Their usage is generally considered a bad practice. Consider reviewing your design a little bit.
I don't know how your application looks like, but say you were doing this:
class TableCreator {
public function createFromId($id) {
global $pdo;
$stmt = $pdo->prepare('SELECT * FROM mytable WHERE id = ?');
$stmt->execute(array($id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
// do stuff
}
}
}
You should do that instead:
class TableCreator {
protected $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function createFromId($id) {
$stmt = $this->pdo->prepare('SELECT * FROM mytable WHERE id = ?');
$stmt->execute(array($id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
// do stuff
}
}
}
Since the TableCreator class here requires a PDO object to work properly, it makes perfect sense to pass one to it when creating an instance.
You'll use $GLOBALS['dbh_pdo'] instead of $dbh_pdo inside any functions. Or you can use the global keyword, and use $dbh_pdo (i.e. global $dbh_pdo).
You could also try using a Singleton to pass back a PDO object to you. That way you only ever have one PDO object (and one database connection) in any request which saves on memory/server resources.
Related
Because I find PDO executions extremely hard to remember and find myself looking back at previous projects or other websites just to remember how to select rows from a database, I decided that I would try and create my own functions that contain the PDO executions and just plug in the data I need. It seemed a lot simpler than it actually is though...
So far I have already created a connect function successfully, but now when it comes to create a select function I'm stumped for multiple reasons.
For starters there could be a variating amount of args that can be passed into the function and secondly I can't figure out what I should pass to the function and in which order.
So far the function looks like this. To keep me sane, I've added the "id" part to it so I can see what exactly I need to accomplish in the final outcome, and will be replaced by variables accordingly when I work out how to do it.
function sql_select($conn, **what to put here**) {
try {
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
print_r($row);
}
} else {
return "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
So far what I've established that the function will need to do is
Connect to the database (using another function to generate the $conn variable, already done)
Select the table
Specify the column
Supply the input to match
Allow for possible args such as ORDER by 'id' DESC
Lastly from this I would need to create a function to insert, update and delete rows from the database.
Or, is there a better way to do this rather than functions?
If anyone could help me accomplish my ambitions to simply simplify PDO executions it would be greatly appreciated. Thanks in advance!
First of all, I have no idea where did you get 10 lines
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = ?');
$stmt->execute(array($id));
$result = $stmt->fetchAll();
is ALL the code you need, and it's actually three lines, which results with a regular PHP array that you can use wherever you wish. Without the need of any PDO code. Without the need of old mysql code.
Lastly from this I would need to create a function to insert, update and delete rows from the database.
DON'T ever do it.
Please read my explanations here and here based on perfect examples of what you'll end up if continue this way.
accomplish my ambitions to simply simplify PDO executions
That's indeed a great ambition. However, only few succeeded in a real real simplification, but most resulted with actually more complex code. For starter you can try code from the first linked answer. Having a class consists of several such functions will indeed improve your experience with PDO.
. . . and find myself looking back at previous projects or other
websites just to remember how to select rows from a database . . .
FYI, we all do that.
You had a problem with the PDO API and now you have two problems. My best and strongest suggestion is this: If you want a simpler/different database API, do not roll your own. Search http://packagist.org for an ORM or a DBAL that looks good and use it instead of PDO.
Other people have already done this work for you. Use their work and focus instead on whatever awesome thing is unique to your app. Work smart, not hard and all that.
Writting a wrapper, should start form connecting the DB, and all the possible method could be wrapped. Passing connection to the query method, doesn't look good.
A very rough example would be the code bellow, I strongly do not suggest this mixture, but it will give you the direction.
You connection should be made either from the constructor, or from another method called in the constructor, You can use something like this:
public function __construct($driver = NULL, $dbname = NULL, $host = NULL, $user = NULL, $pass = NULL, $port = NULL) {
$driver = $driver ?: $this->_driver;
$dbname = $dbname ?: $this->_dbname;
$host = $host ?: $this->_host;
$user = $user ?: $this->_user;
$pass = $pass ?: $this->_password;
$port = $port ?: $this->_port;
try {
$this->_dbh = new PDO("$driver:host=$host;port=$port;dbname=$dbname", $user, $pass);
$this->_dbh->exec("set names utf8");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
So you can either pass connection credentials when you instantiate your wrapper or use default ones.
Now, you can make a method that just recieves the query. It's more OK to write the whole query, than just pass tables and columns. It will not make a whole ORM, but will just make the code harder to read.
In my first times dealing with PDO, I wanted everything to be dynamically, so what I achieved, later I realized is immature style of coding, but let's show it
public function query($sql, $unset = null) {
$sth = $this->_dbh->prepare($sql);
if($unset != null) {
if(is_array($unset)) {
foreach ($unset as $val) {
unset($_REQUEST[$val]);
}
}
unset($_REQUEST[$unset]);
}
foreach ($_REQUEST as $key => $value) {
if(is_int($value)) {
$param = PDO::PARAM_INT;
} elseif(is_bool($value)) {
$param = PDO::PARAM_BOOL;
} elseif(is_null($value)) {
$param = PDO::PARAM_NULL;
} elseif(is_string($value)) {
$param = PDO::PARAM_STR;
} else {
$param = FALSE;
}
$sth->bindValue(":$key", $value, $param);
}
$sth->execute();
$result = $sth->fetchAll();
return $result;
}
So what all of these spaghetti does?
First I though I would want all of my post values to be send as params, so if I have
input name='user'
input name='password'
I can do $res = $db->query("SELECT id FROM users WHERE username = :user AND password = :password");
And tada! I have fetched result of this query, $res is now an array containing the result.
Later I found, that if I have
input name='user'
input name='password'
input name='age'
In the same form, but the query remains with :user and :password and I submit the form, the called query will give mismatch in bound params, because the foreach against the $_REQUEST array will bind 3 params, but in the query I use 2.
So, I set the code in the beginning of the method, where I can provide what to exclude. Calling the method like $res = $db->query("SELECT id FROM users WHERE username = :user AND password = :password", 'age'); gave me the possibility to do it.
It works, but still is no good.
Better have a query() method that recieves 2 things:
The SQL string with the param names
The params as array.
So you can use the foreach() logic with bindValue, but not on the superglobal array, but on the passed on.
Then, you can wrap the fetch methods
public function fetch($res, $mode = null)
You should not directly return the fetch from the query, as it might be UPDATE, INSERT or DELETE.
Just pass the $res variable to the fetch() method, and a mode like PDO::FETCH_ASSOC. You can use default value where it would be fetch assoc, and if you pass something else, to use it.
Don't try to be so abstract, as I started to be. It will make you fill cracks lately.
Hum... IMHO I don't think you should try to wrap PDO in functions, because they're already "wrapped" in methods. In fact, going from OOP to procedural seems a step back (or at least a step in the wrong direction). PDO is a good library and has a lot of methods and features that you will surely lose if you wrap them in simple reusable functions.
One of those features is the BeginTransaction/Rollback (see more here)
Regardless, In a OOP point of view you can decorate the PDO object itself, adding some simple methods.
Here's an example based on your function
Note: THIS CODE IS UNTESTED!!!!
class MyPdo
{
public function __construct($conn)
{
$this->conn = $conn;
}
public function pdo()
{
return $this->conn;
}
public function selectAllById($table, $id = null)
{
$query = 'SELECT * FROM :table';
$params = array('table'=>$table);
if (!is_null($id)) {
$query .= ' WHERE id = :id';
$params['id'] = $id;
}
$r = $this->conn->prepare($query)
->execute($params)
->fetchAll();
//More stuff here to manipulate $r (results)
return $r;
}
public function __call($name, $params)
{
call_user_func_array(array($this->conn, $name), $params);
}
}
Note: THIS CODE IS UNTESTED!!!!
ORM
Another option is using an ORM, which would let you interact with your models/entities directly without bothering with creating/destroying connections, inserting/deleting, etc... Doctrine2 or Propel are good bets for PHP.
Howeveran ORM is a lot more complex than using PDO directly.
I am relatively new to PHP OOP and i know that there are numerous questions here on SO, but none of them seam to be pointing me in the right direction. I have created the class user, and I am calling this in another file.
I am trying to get the method 'reset' to call up 'connect', connect to the mysql db and then query it and set various properties to the row contents.
I am receiving no errors but for some reason it is not feeding the properties any data from the database.
I have tried placing the mySQL connect in the reset method, just to see if the variables cannot be passed between methods. But still no joy.
Can anyone point me in the right direction?
class user(){
public function reset(){
$this->connect();
$sql ='SELECT * FROM users WHERE user_id="'.$user_id.'"' ;
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$this->user_name=$row['dtype'];
$this->user_id=$row['user_id'];
$this->atype=$row['atype'];
$this->user_email=$row['user_email'];
$this->group1=$row['group1'];
$this->group2=$row['group2'];
$this->group3=$row['group3'];
$this->group4=$row['group4'];
$this->group5=$row['group5'];
$this->group6=$row['group6'];
}
// Test that these properties are actually being echoed on initial file... it is
// $this->user_name = "john";
// $this->user_email = "john#gmail.com";
// $this->dtype = "d";
// $this->atype = "f";
}
public function connect(){
//GLOBALS DEFINED IN INDEX.PHP
if ($db_open !== true){
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
$debug_system .= 'Error on user.php: ' . mysqli_connect_error().'<br\/>';
} else {
$db_open = true;
$debug_system .= 'user.php: user details grab successful. <br\/>';
}
}
}
}
If you are relatively new to PHP OOP, it is strongly recommended not to mess with awful mysqli API but learn quite sensible PDO first, and only then, making yourself familiar with either OOP and prepared statements, you may turn to mysqli.
Nevertheless, there shouldn't be no function connect() in the class user. You have to have a distinct db handling class, which instance have to be passed in constructor of user class
The problem lies in this line:
$sql ='SELECT * FROM users WHERE user_id="'.$user_id.'"' ;
At no point do you actually define $user_id. Presumably you actually mean $this->user_id.
$sql ='SELECT * FROM users WHERE user_id="'.$this->user_id.'"' ;
Better still would be to make full use of parameterized queries, which might look like this:
$sql ='SELECT * FROM users WHERE user_id=?' ;
You would then prepare the statement and bind the user ID, then execute the query:
$stmt = mysqli_prepare($sql);
mysqli_stmt_bind_param($stmt, $this->user_id);
mysqli_stmt_execute($stmt);
And then fetch the results:
while($row = mysqli_stmt_fetch($result))
As you can see, there is a whole load more to modern MySQL libraries. I'd advise you to do more research into how MySQLi and parameterized queries work (and perhaps PDO as well: it's a superior library) before you use them further. It will be worth the effort.
In a file, I connect to the database (using PDO) and the resulting connection is called $db, so that queries I run would be something like
$db->query("SELECT money FROM bank_accounts");
However, if I put that line in a function, $db isn't defined so it doesn't work.
Obviously reconnecting to the database in each function isn't the best way to accomplish db calls in a function so how would I accomplish something like
function stealMoney($acctID) {
$db->query("SELECT money FROM bank_accounts WHERE accountID = $acctID");
}
You need to use $db in a function.
And its not defined in the function, so definitely, $db is inaccessible/undefined to the function body.
There are two ways to deal it:
1) Pass $db as an argument to the function.
So, the function body becomes:
function stealMoney($acctID, $db = NULL) {
$db->query("SELECT money FROM bank_accounts WHERE accountID = $acctID");
}
And the function call:
stealMoney($acctID, $db);
2) Use global:
In this case, you can use $db as a global.
So, the function body becomes:
function stealMoney($acctID) {
global $db;
$db->query("SELECT money FROM bank_accounts WHERE accountID = $acctID");
So that, your function will read this variable from outside and can access it.
I am building an abstraction layer over the DB in PHP.
I use PDO and everything works perfectly in a pure imperative script.
Now i want to swap this bunch of code (a web service API) to an OOP approach with MVC and i am trying to abstract the DB interface to have calls like (in a race db enviroinment) getRaceList(); or getRookieAthlets(); etc from and present them whereever else.
It would work perfectly if i would do something like this in the persistance class to be called
class Persistantance{
//other methods
/**
* return all races
**/
public function getRaces(){
$result = null;
try {
$db = $this->connect(); //return a PDO object
$query = "SELECT races.title, races.year, races.id FROM races;";
//here use prepared statement statements if needed
$result = $db->query($query);
$races = array();
foreach ($result as $record) {
//here insert $record in $races
}
$result->closeCursor();
$db = null;
}catch(PDOException $e){
// Print PDOException message
echo $e->getMessage();
}
return $races;
}
}
class View{
public function viewRaces(){
//...
$races = $pers->getRaces();
foreach($races as $race)
printRecord($race);
//...
}
}
It would work, but just like $stmnt->fetchAll() its very memory intensive since it brings everything in memory. Db is pretty big, but due to impagination it's unlikely i'll get very big arrays, but i'd like to know a pattern to be as much as size-independent as possible.
On the other side if i build an iterator i'd complicate the Persistance interface a lot(i want to distribute the interface):
//from a view class
perist->a_query()
repeat untill null
perist->fetch_last_query_next()
perist->close_conn()
Moreover it wouldn't be possible to perform more queries in parallel if not complicating even more the interface with multiple iterators method.
In the past I would just create a class to connect to a database, and then run a bunch of methods to run queries.. like so:
class connectDB
{
public $db_host = "asdf.db.asdf.hostedresource.com";
public $db_name = "asdf";
public $db_user = "asdf";
public $db_pass = "asdf!1";
public $result;
function setDB_Host($value){
$this->db_host=$value;
}
function setDB_name($value){
$this->db_name=$value;
}
function setDB_user($value){
$this->db_user=$value;
}
function setDB_pass($value){
$this->db_pass=$value;
}
function makeConnection()
{
$connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass) or die
("Unable to connect!");
mysql_select_db($this->db_name) or die(mysql_error());
}
function setQuery($query)
{
$this->result = mysql_query($query) or die(mysql_error());
}
class video
{
public $sequence;
public $fileName;
public $vidTitle;
public $vidCat;
public $thumbName;
function addVideo($sequence, $fileName, $vidTitle, $vidCat, $thumbName)
{
$this->connect-> setQuery("SELECT COUNT(id) AS numrows FROM vids WHERE vidCat = '$vidCat'");
$row = mysql_fetch_array($this->connect->result);
$sequence = $row['numrows'] + 1;
$this->connect->setQuery("INSERT INTO vids (sequence, fileName, vidTitle, vidCat, thumbName) VALUES ('$sequence', '$fileName', '$vidTitle', '$vidCat', '$thumbName') ");
}
function addKeypoints($keypoints, $mins, $secs)
{
$v_id = mysql_insert_id();
for ($i=0; $i<sizeof($keypoints); $i++)
{
$totalsecs = ($mins[$i]*60) + $secs[$i];
$this->connect->setQuery("INSERT INTO keypoints (v_id, totalsecs, keypoints, mins, secs) VALUES ('$v_id', '$totalsecs', '$keypoints[$i]', '$mins[$i]', '$secs[$i]') ");
}
}
without wanting to read all that. Basically I just run a bunch of methods that access my first class, and run queries. I don't understand how this would work in a PDO context. PDO should be making this sort of thing easier since it's OOP based.. correct?
$hostname = "aaa.db.7149468.aaa.com";
$username = "coolcaaaaodez";
$password = "aaaa";
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=coolcodez", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO links (link, cool, difficulty) values (:link, :cool, :difficulty)");
$stmt->bindParam(':link', $_POST['link']);
$stmt->bindParam(':cool', $_POST['cool']);
$stmt->bindParam(':difficulty', $_POST['difficulty']);
if(isset($_POST['submit-links']))
{
$stmt->execute();
echo "row added <br />";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
basically what i'm asking is.. the try / catch thing really trips me up. Does just the connection itself need to be put into a try / catch block, and then I could prepare queries within each of my methods belonging to a class? Or does each sequence of events (database connection, query, results, etc) need to be stuck within a try / catch block. PDO is a little fancy for my needs, but I'm trying to learn, and I'd like to know the best general way to write it when a large number of queries are involved.
PDO should be making this sort of thing easier since it's OOP based.. correct?
Yes... in a way.
Being fine instrument, OOP requires some skill in using - only then it will make things easier indeed. Otherwise, it will make things quite harder.
All the code you need, actually, is
if(isset($_POST['submit-links']))
{
require 'pdo.php';
$sql = "INSERT INTO links (link, cool, difficulty) values (?, ?, ?)";
$data = array($_POST['link'], $_POST['cool'], $_POST['difficulty']);
$dbh->prepare($sql)->execute($data);
}
The rest of your code is superfluous for two reasons:
surely DB connection code should be stored in a separate file and included in all other files, instead of being duplicated each time. A good example for the connection code can be found in the PDO tag wiki
This try-catch stuff, which indeed confuse many inexperienced developers. In fact, you don't need it here at all - or, at least, not in this form. Just because PHP can handle the error itself (and do it better than average PHP user, to be honest). So, you can just omit this try/catch stuff. Further reading: The (im)proper use of try..catch.
Think about it this way - for any error that PDO might encounter, it will throw an exception. WHen using the mysql_ functions, they either just return FALSE/NULL or give you a notice, a warning or even a fatal error. With PDO, you do not get errors, you get exceptions. So you can catch something that mysql_ would have caused to stop the script all together.
So in the end, you probably want to have a try/catch block around every call that could result in some kind of error, and you know how to handle it. If that disturbs your eye, you can write a short class extending PDO that would do the try/catch logic inside and return you either the results or FALSE/NULL as would mysql_ functions do.