1

我目前正在将 MySQL 转换为 PDO,我不确定我是否正确编写了这个函数,我也不确定如何使用 sqlfiddle,所以我求助于 Stackoverflow。如果正确,有什么可以改善当前代码的吗?

MySQL 示例:

    PUBLIC FUNCTION Insert_Update($_iD, $update, $uploads){
    $update     = mysql_real_escape_string($update);
    $time       = time();
    $_iP        = $_SERVER['REMOTE_ADDR'];
    $query      = mysql_query("SELECT post_iD,message FROM `Posts` WHERE uid_fk='$_iD' ORDER by post_iD DESC LIMIT 1") or die(mysql_error());
    $result     = mysql_fetch_array($query);

        if ($update!=$result['message']) {
            $uploads_array  = explode(',',$uploads);
            $uploads        = implode(',',array_unique($uploads_array));
            $query      = mysql_query("INSERT INTO `Posts` (message, uid_fk, _iP,created,uploads) VALUES (N'$update', '$_iD', '$_iP','$time','$uploads')") or die(mysql_error());
            $newquery       = mysql_query("SELECT M.post_iD, M.uid_fk, M.message, M.created, U._iUsername FROM Posts M, users U where M.uid_fk=U._iD and M.uid_fk='$_iD' order by M.post_iD desc limit 1 ");
            $result         = mysql_fetch_array($newquery);
            return $result;

            } else {
            return false;
        }
}

PDO 示例:

    PUBLIC FUNCTION Insert_Update($_iD, $update, $uploads){
$sth = $this->db->prepare("SELECT post_iD,message FROM `Posts` WHERE uid_fk = :id ORDER by post_iD DESC LIMIT 1")
$sth->execute(array('id' => $_iD));
$result = $sth->FetchAll(PDO::FETCH_ASSOC);

        if ( $update!=$result['message'] ){
            $uploads_array  = explode(',',$uploads);
            $uploads        = implode(',',array_unique($uploads_array));
            $sth = $this->db->prepare("INSERT INTO Posts (message, uid_fk, _iP,created,uploads) VALUES ( :update, :id, :ip, :time, :uploads)")
            $sth->bindValue(':update', $update);
            $sth->bindValue(':id', $_iD);
            $sth->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
            $sth->bindValue(':time', time());
            $sth->bindValue(':uploads', $uploads);
            $sth->execute()

            $sth = $this->db->prepare("
                                        SELECT M.post_iD, M.uid_fk, M.message, M.created, U._iUsername 
                                        FROM Posts M, users U 
                                        WHERE M.uid_fk=U._iD 
                                        AND M.uid_fk = :id 
                                        ORDER by M.post_iD DESC LIMIT 1 ");
            $sth->execute(array(':id' => $_iD));
            $result = $sth->FetchAll(PDO::FETCH_ASSOC);
            return $result;
            } else {
            return false;
        }
}
4

0 回答 0