将Mysql更改为PDO

i am trying to create a shopping using PDO. So far i have done it the older ways and i have been trying for the past 6 days to do this in PDO. Please someone help. How will i do that it PDO

dbconnect();
    $i = 0; 
    foreach ($_SESSION["cart_array"] as $each_item) { 
        $item_id = $each_item['item_id'];
        $sql = mysql_query("SELECT * FROM product WHERE ID='$item_id' LIMIT 1");
        while ($row = mysql_fetch_array($sql)) {
            $product_name = $row["Name"];
            $price = $row["Cost"];
            $details = $row["Description"];
        }

Guessing that your dbconnect() function contains the code to create a connection to the database. Here's how to set up a good PDO connection:

try {
    $pdo = new PDO($dsn, $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
} 

You can read docs on the MySQL format for $dsn here: http://www.php.net/manual/en/ref.pdo-mysql.php

Then the other parts of your code would be something like this:

foreach ($_SESSION["cart_array"] as $each_item) { 
    $item_id = $each_item["item_id"];
    $sql = "SELECT * FROM Hair_category WHERE Hair_ID=:item_id LIMIT 1");
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(":item_id"=>$item_id));
    while ($row = $stmt->fetch()) {
        $product_name = $row["Name"];
        $price = $row["Start_Cost"];
        $details = $row["Brief_Description"];
    }
}

If this causes any error, it will throw an exception, since I set that attribute right after the connection was created.

As a matter of fact, your current code is quite inefficient. Instead of running several queries, run only one to get all items

dbconnect();
if($_SESSION["cart_array"]) { 
    // that's quite tricky part. 
    // have to create a string of placeholders like  ?,?,?
    $in  = str_repeat('?,', count($_SESSION["cart_array"]) - 1) . '?';
    // the rest is quite simple:
    $sql = "SELECT * FROM Hair_category WHERE Hair_ID= IN($in)";
    $stm = $pdo->prepare($sql);
    $stm->execute($_SESSION["cart_array"]);
    $data = $stm->fetchAll();
}

Now you have all the items in $data array and can iterate it somewhere else (in a template probably)

Proper code for dbconnect() you can see in the tag wiki

I did it this way and it work. Thanks for all your help everyone

$total_cart_items = count($_SESSION["cart_array"]);
dbconnect();
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$stmt = $conn->prepare("SELECT * FROM product WHERE pid=:id");
$stmt->bindParam('id',$item_id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$product_name = $row["Name"];
$price = $row["Cost"];
$details = $row["Description"];
}