Php准备语句第一步错误

时间:2013-04-16 22:43:34

标签: php pdo prepared-statement

我刚开始学习一小时前的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");  

感谢。

2 个答案:

答案 0 :(得分: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']);

connection.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);

答案 1 :(得分: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);