将MySQL更改为PDO

时间:2015-04-21 09:08:12

标签: mysql database pdo

我必须将旧的mysql更改为PDO,我正在使用其他人制作的代码,所以我在PDO中更改了以下代码 原始代码是

function liste($a,$b,$c)
{
        $queryliste= "SELECT id,nom,prenom
        FROM table";
        $this->list =  Connection_Base($querylistactu);
}

//Connection_Base
function Connection_Base($query)
{
    $link = mysql_connect(DATABASESERVER, DATABASEUSER, DATABASEPASSWORD);
    $ret = mysql_select_db(DATABASEDB, $link);
    if (!$ret)
    {
        die("Echec de connection");
    } else {
        $mysql_desc = DATABASEDB;
        if(!$result = mysql_query( $query))
        {
            return 0;
        } else {
            return $result;
        }
        mysql_close($link);
    }
}

这是我遇到问题的部分。我想用PDO改变它。

while( list($x,$y,$z) = mysql_fetch_row($lactu->list) )

我这样继续但是它不起作用

while( list($x,$y,$z) = $lactu->list->fetch(PDO::FETCH_NUM) 

任何想法?

1 个答案:

答案 0 :(得分:0)

为什么不使用PDO :: FETCH_ASSOC?检查代码示例以连接到数据库,执行查询,获取所有行并迭代行。

//Your query
$queryliste = "SELECT id, nom, prenom FROM table";

//Initialize pdo connection use your $name, $host, $username and $password
$pdoLink = new PDO("mysql:dbname={$name};host={$host};charset=utf8", $username, $password);

//Prepare statement
$statement = $pdoLink-> prepare($queryliste);
//Execute query
$statement -> execute();

//(1) Fetch rows using PDO::FETCH_ASSOC
$rows = $statement -> fetchAll(PDO::FETCH_ASSOC);
$statement -> closeCursor();
foreach($rows as $row) {
    echo $row['id'];
    echo $row['nom'];
    echo $row['prenom'];
}

//(2) or you can use PDO::FETCH_NUM
$rows = $statement -> fetchAll(PDO::FETCH_NUM);
$statement -> closeCursor();

foreach($rows as list($x, $y, $z)) {
    echo $x;
    echo $y;
    echo $z;
}

//(3) or you can rewrite the last in the same form you are using as 
while((list($x, $y, $z) = $statement->fetch(PDO::FETCH_NUM))) {
    echo $x;
    echo $y;
    echo $z;
}
$statement -> closeCursor();