-1

我刚开始学习 php 准备好的语句,就像一小时前一样。我需要一些帮助来将此功能转换为 PDO。一直在尝试,但遇到了很多错误。

    function titleQuery($ligaBD){
                $query1="SELECT title FROM page WHERE id='".$_GET['id']."'";
                $result1=mysqli_query($ligaBD,$query1);
                $registos1 = mysqli_fetch_array($result1);

                return $registos1; 
}

以及如何保留我的 connection.php 文件?应该一直这样吗?

$db_host = "localhost"; 
$db_username = "root";  
$db_password = "";
$db_name = "mpm"; 

$ligaBD = mysqli_connect("$db_host","$db_username","$db_password","$db_name") or die ("Error");  

谢谢。

4

2 回答 2

1

要将此函数转换为 PDO,您需要使用 PDO 的东西。

function titleQuery($db,$id)
{
    $sql = "SELECT title FROM page WHERE id=?";
    $stm = $db->prepare($sql);
    $stm->execute(array($id));
    return $stm->fetchColumn();
}

$title = titleQuery($ligaBD,$_GET['id']);

连接.php

$dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$ligaBD = new PDO($dsn, $db_username, $db_password, $opt);
于 2013-04-16T22:52:45.233 回答
0

如何将查询结果放入 PDO 上的变量中?

在此行上出现错误“无法使用 PDOStatement 类型的对象作为数组”:

if($stm['acess'] == 0){ echo'.....'; }

函数上的注释代码是我试图从 mysqli 转换为 PDO 的代码

function checkPageAcess($ligaBD,$acess){ // Check if page is Private or Public
            /*$registos1=titleQuery($ligaBD,$_GET['id']);

            $query2= "SELECT acess FROM statistic WHERE id_page IN(SELECT id FROM page WHERE title='".$registos1['title']."')";
            $result2 = mysqli_query($ligaBD,$query2);
            $registos2 = mysqli_fetch_array($result2);

            if($registos2['acess']==0){
                echo '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Easy Page Builder</title></head><body>This page is private.</body></html>';exit;
            }*/


            $sql = "SELECT acess FROM statistic WHERE id_page IN(SELECT id FROM page WHERE title=?)";
            $stm = $ligaBD->prepare($sql);
            $stm->execute(array($acess));
            $stm->fetchColumn();

            if($stm['acess'] == 0){
                echo '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Easy Page Builder</title></head><body>This page is private.</body></html>';exit;
            }
    }
    $acess = checkPageAcess($ligaBD,$title);
于 2013-04-17T13:20:12.007 回答