Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I realize this is probably super simple but i just started taking peoples advice and im converting a small program from mysql to PDO as an attempt to learn and switch to PDO.

The script is a script that shows you how to build a shopping cart, so keep in mind its focused on a learning audience like myself. Anyway i converted the old script here:

function db_connect()
{
    $connection = mysql_pconnect('localhost', 'database_1', 'password');

    if(!$connection)
{
    return false;
}
if(!mysql_select_db('database_1'))
{
    return false;
}

    return  $connection;
}

to this which does connect fine:

function db_connect() {
//Hostname
$hostname = 'xxx.com';

//username
$username = 'xxx';

//password
$password = 'xxx';

try {
$connection = new PDO("mysql:host=$hostname;dbname=database_1", $username, $password);
}
catch(PDOException $e){
echo $e->getMessage();
}   
}

Now in other parts of the script before accessing the database it does this:

$connection = db_connect();

Now i have 2 questions. First is to help me understand better what is going on.

I understand in the original mysql function we connect to the database, if the connection is unsuccessful or the database doesnt exist it returns false. If it does connect to the database then it returns true.

With that i mind i dont understand this:

$connection = db_connect();

Isnt that just assigning true or false to the $connection variable, if so then whats going on in this part of the code.

$price = 0.00;
$connection = db_connect();

if (is_array($cart)) 
{
    foreach($cart as $id => $qty)
    {
        $query = "SELECT price
                    FROM products
                    WHERE products.id = '$id' ";

        $result = mysql_query($query);
        if($result)
        {
            $item_price = mysql_result($result, 0, 'price');
            $price += $item_price * $qty;   
        }

    }

}

Instead couldn't i just create an include file with the PDO connection and no function and include that at the top of each page i run scripts on. I just don't understand where the $connection = db_connect comes in.

So the 2nd question if my above suggestion is not the answer is how do i return a boolean value from the connection function to return true or false (If i even need to)

share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

There is one essential difference between old mysql and PDO: both these libraries require a resource variable to connect with. If you take a look at mysql_query() function definition, you will notice the second parameter, represents such a resource.

$connection variable returned by your old function by no means contain boolean value but such a resource variable. Which can be used in every mysql_query call.

But while for mysql ext this resource parameter being optional, and used automatically when not set, with PDO you have to address this resource variable explicitly. Means you cannot just call any PDO function anywhere in the code, but only as a method of existing PDO object. Means you have to make this variable available wherever you need PDO.

Thus, you need not a boolean but PDO object.

Here is the right code for the function:

function db_connect()
{
    $dsn = "mysql:host=localhost;dbname=test;charset=utf8";
    $opt = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    return new PDO($dsn,'root','', $opt);
}

now you can use it this way

$pdo = db_connect();

but note again - unlike with mysql_query(), you have to always use this $pdo variable for your queries.

Further reading is PDO tag wiki

share|improve this answer
 
Thanks for everyones help, after a bit of reading it makes a lot of sense now although initially reading these replies i was still a bit confused, i have to say its not that hard converting to PDO even for a newbie so thanks all for your help –  user1547410 Jul 30 '13 at 11:02
add comment

As you guessed from the context, db_connect() is supposed to return the connection object. Your converted version doesn't return anything, which is a problem.

With the mysql module, you can run queries without using the connection object - this is not the case with PDO. You'll need to use the connection object to run any queries -

$result = $connection->query('SELECT * FROM foo');
share|improve this answer
add comment

First off, let me congratulate you for making the effort to learn PDO over mysql_*. You're ahead of the curve!

Now, a few things to understand:

  • PDO is OO, meaning the connection to the database is represented by a PDO Object.
  • Your db_connect() function should return the object that gets created.
  • Passing in the parameters required by PDO will give you more flexibility!

So what we have is:

function db_connect($dsn, $username, $password) 
{
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //This makes sure that PDO will throw PDOException objects on errors, which makes it much easier enter code hereto debug.
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //This disables emulated prepared statements by PHP, and switches to *true* prepared statements in MySQL.

    return $conn; //Returns the connection object so that it may be used from the outside.
}

Now, you may have noticed we aren't checking for PDOExceptions inside of the function! That's because you can't handle the error from inside of the function correctly (becuase you don't know what you would want to do? Would you terminate the page? Redirect to an error message?). So you can only know it when you call the function.

So usage:

try {
    $connection = db_connect("mysql:host=$hostname;dbname=database", "user", "pass");
}
catch (PDOException $e) {
    echo "Database error! " . $e->getMessage();
}

Further Reading!

  • The PDO Manual entry - is super easy and super useful. I recommend you read all of it.
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.