加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – ChangingCode从MySQL到PDO

发布时间:2020-12-13 16:26:52 所属栏目:PHP教程 来源:网络整理
导读:我使用 MySQL语法编写了一个CMS脚本. 我想用PDO语法替换MySQL语法.有人可以帮我做,并向我解释如何做到这一点? 这是脚本中的代码. ?php $querytemp = mysql_query("select * from main_setting") or die (mysql_error()); $row = mysql_fetch_object($queryt
我使用 MySQL语法编写了一个CMS脚本.

我想用PDO语法替换MySQL语法.有人可以帮我做,并向我解释如何做到这一点?

这是脚本中的代码.

<?php
    $querytemp = mysql_query("select * from main_setting") or die (mysql_error());
    $row = mysql_fetch_object($querytemp);

    include "inc/upcenter_block.php";

    echo "
        <div class='headmenu'>$row->news1</div>
        <div class='bodymenu'>
        <p>".nl2br($row->news)."</p>
    </div> ";

    include "inc/downcenter_block.php";
?>
首先,如果你想从mysql_ *更改为PDO

您需要更改脚本中的所有代码,而不仅仅是a
单一的,不会工作

如果你要将代码从mysql_ *更改为PDO

您将不得不使用PDO更改与数据库的连接

这是一个样本:

// here we set the variables 
$dbhost = "localhost";
$dbname = "testcreate";
$dbuser = "root";
$dbpass = "mysql";

// here we are using ( try {} ) to catch the errors that will shows up and handle it in a nicer way
    try {
    $db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname.';charset=utf-8',''.$dbuser.'',''.$dbpass.'');
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo 'Error : <br>' . $e->getMessage();
    }
// here we set the varible for the connection = then starting the cennction with new POD();
$db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname.';charset=utf-8',''.$dbpass.'');
// here we set an Attribute to handle the errors
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
// you dont need to use it in our case because we already catching the error and handling it in out way
// here we catch the error then handling it by echo a msg and then we used
  // $e->getMessage(); to get the error msg that should be throwing in the page
    catch (PDOException $e) {
        echo 'Error : <br>' . $e->getMessage();
    }

——————————————–

现在我们完成了连接
我将向您展示如何查询和获取表

// this is how we will use query
 $qr = $db->query()

 // and this is how to fetch it by taking the query variable and use the arrow then fetch 
 $ro = $qr->fetch()

我将为您展示一个代码示例

$querytemp = mysql_query("select * from main_setting") or die (mysql_error());
$row = mysql_fetch_object($querytemp);

我们会改变这个

$querytemp = $db->query("select * from main_setting");
$row = $querytemp->fetch(PDO::FETCH_OBJ);

所以现在你可以在PDO上使用$row-> news

现在您可以轻松地将代码更改为PDO

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读