我该如何将这个mysql代码更改为pdo?

时间:2013-08-05 13:05:59

标签: mysql pdo

我在iclude中有这个代码用于连接数据库 我在这个文件中也有mysql连接函数,但我决定将mysql更改为pdo -include.php:

try{
    $conn = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
    return $conn;
}
catch(PDOException $e)
{
    echo 'can not connect to database';
    exit();
}

我在index.php中有mysql查询,但我想将此代码更改为pdo

<?php
$sql=mysql_query("SELECT id,col1 FROM tblname ORDER BY col4 DESC, col3 DESC, tzade DESC LIMIT 18");
if(mysql_num_rows($sql)) {
$j=0;
    while($result = mysql_fetch_object($sql)) {

$j++;
if($result->id == $site_id){
?>
<a class="normal_link" href="l.php?lid=<?php echo $result->id; ?>&title=<?php echo title($result->col1);?>">
<div id="jadv">
<div><?php echo $j; ?></div>
<div><?php echo $result->col1; ?></div>
</div>
</a>
<?php
}
else{
?>
<a class="normal_link" href="l.php?lid=<?php echo $result->id; ?>&title=<?php echo title($result->col1);?>">
<div id="jadva">
<div id="jad"><?php echo $j; ?></div>
<div id="jad"><?php echo $result->col1; ?></div>
</div>
</a>
<?php
}
}
}
?>

如何将此代码中的mysql查询更改为pdo?

3 个答案:

答案 0 :(得分:0)

  1. 阅读一些教程(甚至还有很多here on SO
  2. 运行一些简单的查询以熟悉PDO
  3. 从重写开始。

答案 1 :(得分:0)

你应该阅读一些关于PDO的文档并做一些教程。但是为了帮助您,这是一个从PDO开始的非常简单的示例:

<?php
$connexion = new PDO("mysql:host=$PARAM_hote;dbname=$PARAM_db_name", $PARAM_user, $PARAM_pwd); // DB connexion

$results=$connection->query("SELECT member FROM member ORDER BY member ASC"); // retrieving all entries from member table 
$results->setFetchMode(PDO::FETCH_OBJ); // retrieving results as objects
while( $lines= $results->fetch() ) // retrieving list of member
{
        echo 'user: '.$lines->member.'<br />'; // displaying members
}
$results->closeCursor(); // close results cursor
?>

这里有一个更复杂的params(准备好的查询):

<?php
// connection opening ...

$prepared_query=$connecion->prepare("SELECT id FROM member WHERE member_id= :id"); // query prepare
$prepared_query->execute(array( 'id' => 1 ));
$lines=$prepared_query->fetch(PDO::FETCH_OBJ);
echo $lines->id.'<br />';
?>

这是我的一个旧样本,我希望能帮助你。

答案 2 :(得分:-1)

这样的事情:

<?php
$sql = "SELECT id,col1 FROM tblname ORDER BY col4 DESC, col3 DESC, tzade DESC LIMIT 18 ";
$sth = $conn->query($sql);
$sth->setFetchMode(PDO::FETCH_ASSOC);

if ($count = $sth->rowCount() > 0){
$j=0;
    while ($row = $sth->fetch()) {

$j++;
if($row['id'] == $site_id){
?>
<a class="normal_link" href="l.php?lid=<?php echo $row['id'] ?>&title=<?php echo title($row['col1']);?>">
<div id="jadv">
<div><?php echo $j; ?></div>
<div><?php echo $row['col1'] ?></div>
</div>
</a>
<?php
}
else{
?>
<a class="normal_link" href="l.php?lid=<?php echo $row['id'] ?>&title=<?php echo title($row['col1']);?>">
<div id="jadva">
<div id="jad"><?php echo $j; ?></div>
<div id="jad"><?php echo $row['col1'] ?></div>
</div>
</a>
<?php
}
}
}
?>