-1

我在 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?

4

3 回答 3

0
  1. 阅读一些教程(甚至在 SO 上也有很多)
  2. 运行一些简单的查询来熟悉 PDO
  3. 从重写开始。
于 2013-08-05T13:17:34.963 回答
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
?>

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

<?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 />';
?>

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

于 2013-08-05T13:26:08.830 回答
-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
}
}
}
?>
于 2013-08-05T13:23:26.253 回答