2

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)

4

3 回答 3

1

旧的 mysql 和 PDO 之间有一个本质区别:这两个库都需要一个资源变量来连接。如果你看一下mysql_query()函数定义,你会注意到第二个参数,代表这样一个资源。

$connection旧函数返回的变量绝不包含布尔值,而是这样的资源变量。可以在每个 mysql_query 调用中使用。

但是对于 mysql ext,此资源参数是可选的,并且在未设置时自动使用,但使用 PDO,您必须显式处理此资源变量。意味着您不能只在代码中的任何位置调用任何 PDO 函数,而只能作为现有 PDO 对象的方法。意味着您必须在需要 PDO 的任何地方使该变量可用。

因此,您不需要布尔值而是 PDO 对象。

这是该函数的正确代码:

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);
}

现在你可以这样使用它

$pdo = db_connect();

但再次注意 - 与 mysql_query() 不同,您必须始终使用此$pdo变量进行查询。

进一步阅读是PDO 标签 wiki

于 2013-07-29T06:03:51.610 回答
0

首先,让我祝贺你努力学习 PDO over mysql_*。你走在了曲线的前面!

现在,有几点需要理解:

  • PDO 是OO,这意味着与数据库的连接由PDOObject表示。
  • 您的db_connect()函数应返回创建的对象。
  • 传入 PDO 所需的参数会给你更大的灵活性!

所以我们有的是:

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.
}

现在,您可能已经注意到我们没有在函数内部检查 PDOExceptions!那是因为您无法从函数内部正确处理错误(因为您不知道要做什么?您会终止页面吗?重定向到错误消息?)。所以只有调用函数时才能知道。

所以用法:

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

进一步阅读!

  • PDO 手册条目-非常简单且非常有用。我建议您阅读所有内容。
于 2013-07-28T21:03:00.117 回答
0

正如您从上下文中猜到的,db_connect()应该返回连接对象。您转换后的版本没有返回任何内容,这是一个问题。

使用该mysql模块,您可以在不使用连接对象的情况下运行查询 - PDO 不是这种情况。您需要使用连接对象来运行任何查询 -

$result = $connection->query('SELECT * FROM foo');
于 2013-07-28T20:53:51.513 回答