我想将MySQL查询转换为PDO?

时间:2012-09-19 19:32:43

标签: php mysql pdo

我需要将其转换为PDO表格,但由于我是所有这一切的新手,有人可以帮助我吗?我的教授声称每个功能都可以转换,但我找不到任何可以帮助我的东西。

<?php
    // rnfunctions.php
    $dbhost = 'localhost';
    $dbname = 'social_local';
    $dbuser = 'root';
    $dbpass = 'root';
    $appname = "Social Networking Test Site";
    try
    {
        $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    }
    catch ( PDOException $e )
    {
        echo $e->getMessage();
    }

    function createTable ($name, $query)
    {
        if (tableExists($name)) {
            echo "Table '$name' already exists<br />";
        } else {
            queryMysql("CREATE TABLE $name($query)");
            echo "Table '$name' created<br />";
        }
    }

    function tableExists ($name)
    {
        $result = queryMysql("SHOW TABLES LIKE '$name'");
        return mysql_num_rows($result);
    }

    function queryMysql ($query)
    {
        $result = mysql_query($query) or die(mysql_error());
        return $result;
    }

    function destroySession ()
    {
        $_SESSION = array();
        if (session_id() != "" || isset($_COOKIE[session_name()])) {
            setcookie(session_name(), '', time() - 2592000, '/');
        }
        session_destroy();
    }

    function sanitizeString ($var)
    {
        $var = strip_tags($var);
        $var = htmlentities($var);
        $var = stripslashes($var);
        return $var;
    }

    function showProfile ($user)
    {
        if (file_exists("$user.jpg")) {
            echo "<img src='$user.jpg' border='1' align='left' />";
        }
        $result = queryMysql("SELECT * FROM rnprofiles WHERE user='$user'");
        if (mysql_num_rows($result)) {
            $row = mysql_fetch_row($result);
            echo stripslashes($row[1]) . "<br clear=left /><br />";
        }
    }
    ?>

2 个答案:

答案 0 :(得分:1)

您需要首先实例化一个PDO类。然后学习PDO功能。

$dbh = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$stmt = $dbh->prepare($sql);
$stmt->execute();
return $stmt;

使用类似$stmt->FetchAll()的内容来获取结果。

答案 1 :(得分:0)

这样的事可能会对你有所帮助:

$dbh = new PDO("mysql:host=localhost;dbname=yourBaseName", 'someLogin', 'somePassword');
$dbh->prepare('SELECT login FROM members WHERE login=? AND password=?');
$stm = $dbh->execute(array($login, $pass));
if (($row = $stm->fetchObject())) {
    echo "You are loggued!";
    // stuffs with loggued user
} else {
    echo "Invalid user or password";
    // login form again
}