2017-12-02 309 views
0

我試圖通過PDO從PHP獲取數據,然後接收一個JSON對象(json_encode)以在前端使用某些東西。嘗試爲我可能,我從MySQL查詢得到的唯一數據是誰添加的消息(微博)的用戶的用戶名,見下圖: enter image description herephp - 查詢數據到json響應

分享Tweet類:從資料Tweet類

class Tweet extends User { 

private $id; 
private $userId; 
private $text; 
private $creationDate; 

public function __construct() { 
    $this->id = -1; 
    $this->userId = null; 
    $this->text = null; 
    $this->creationDate = null; 
} 

function getId() { 
    return $this->id; 
} 

function getUserId() { 
    return $this->userId; 
} 

function getText() { 
    return $this->text; 
} 

function getCreationDate() { 
    return $this->creationDate; 
} 

function setUserId($userId) { 
    $this->userId = $userId; 
} 

function setText($text) { 
    $this->text = $text; 
} 

function setCreationDate($creationDate) { 
    $this->creationDate = $creationDate; 
} 

static public function loadTweetById(PDO $pdo, $id) { 
    $stmt = $pdo->prepare("SELECT * FROM Messages WHERE message_id=:id"); 
    $result = $stmt->execute([ 
     'id' => $id 
    ]); 

    if ($result === true && $stmt->rowCount() > 0) { 
     $row = $stmt->fetch(PDO::FETCH_ASSOC); 

     $loadedTweet = new Tweet(); 
     $loadedTweet->id = $row['message_id']; 
     $loadedTweet->userId = $row['user_id']; 
     $loadedTweet->text = $row['message_text']; 
     $loadedTweet->creationDate = $row['message_datetime']; 

     return $loadedTweet; 
    } 

    return null; 
} 

static public function loadAllTweetsByUserId(PDO $pdo, $id) { 
    //$stmt = $pdo->prepare("SELECT * FROM Messages WHERE user_id=:id"); 
    $stmt = $pdo->prepare("SELECT " 
      . "Users.username, " 
      . "Messages.message_text, " 
      . "Messages.message_datetime " 
      . "FROM " 
      . "Messages " 
      . "JOIN " 
      . "Users " 
      . "ON Users.id=Messages.user_id " 
      . "WHERE `user_id`=:id " 
      . "ORDER BY Messages.message_datetime DESC"); 
    $result = $stmt->execute([ 
     'id' => $id 
    ]); 

    //var_dump($stmt->rowCount()); 


    if ($result === true && $stmt->rowCount() > 0) { 
     while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 

      $loadedTweet = new Tweet(); 
      //echo $loadedTweet->id = $row['message_id'] . '<br>'; 
      echo $loadedTweet->userId = $row['username'] . '<br>'; 
      echo $loadedTweet->text = $row['message_text'] . '<br>'; 
      echo $loadedTweet->creationDate = $row['message_datetime'] . '<br>'; 
      echo "<br>"; 


      //return $loadedTweet; 
     } 

     return null; 
    } 
} 

static public function loadAllTweets(PDO $pdo) { 

    $sql = "SELECT * FROM Messages JOIN Users ON Users.id=Messages.user_id ORDER BY Messages.message_datetime DESC"; 

    $stmt = $pdo->prepare($sql); 
    $stmt->execute(); 

    $tweets = $stmt->fetchAll(PDO::FETCH_OBJ); 
    $tweetsList = []; 

    if ($stmt !== false && $stmt->rowCount() > 0) { 
     foreach ($tweets as $dbTweet) { 
      $tweet = new Tweet($pdo); 
      $tweet->id = $dbTweet->message_id; 
      $tweet->userId = $dbTweet->user_id; 
      $tweet->text = $dbTweet->message_text; 
      $tweet->creationDate = $dbTweet->message_datetime; 
      $tweet->getUsername = $dbTweet->username; 


      $tweetsList[] = $tweet; 
     } 
     return $tweetsList; 
    } else { 
     return null; 
    } 

} 

public function saveToDB(PDO $pdo) { 
    //sprawdza czy robimy insert czy update 
    if ($this->id == -1) { // if -1, robimy insert 
     //przygotowanie zapytania 
     //$userId = $_SESSION['userId']; 
     $sql = "INSERT INTO `Messages`(`user_id`, `message_text`) VALUES (:user_id, :message_text)"; 
     $prepare = $pdo->prepare($sql); 

     //wyslanie zapytania do bazy z kluczami i wartosciami do podmienienia 
     $result = $prepare->execute([ 
      //uzywa userId zapisanego w sesji 
      'user_id' => $this->userId, 
      'message_text' => $this->text 
     ]); 

     // pobranie ostatniego ID dodanego rekordu i przypisanie do ID w tabeli Users 
     //$this->id = $pdo->lastInsertId(); 


     return (bool) $result; 
    } 
} 

功能loadAllTweets (返回資料Tweet對象的數組):

static public function loadAllTweets(PDO $pdo) { 

    $sql = "SELECT * FROM Messages JOIN Users ON Users.id=Messages.user_id ORDER BY Messages.message_datetime DESC"; 

    $stmt = $pdo->prepare($sql); 
    $stmt->execute(); 

    $tweets = $stmt->fetchAll(PDO::FETCH_OBJ); 
    $tweetsList = []; 

    if ($stmt !== false && $stmt->rowCount() > 0) { 
     foreach ($tweets as $dbTweet) { 
      $tweet = new Tweet(); 
      $tweet->id = $dbTweet->message_id; 
      $tweet->userId = $dbTweet->user_id; 
      $tweet->text = $dbTweet->message_text; 
      $tweet->creationDate = $dbTweet->message_datetime; 
      $tweet->getUsername = $dbTweet->username; 


      $tweetsList[] = $tweet; 
     } 
     return $tweetsList; 
    } else { 
     return null; 
    } 

} 

mainpage.php

<?php 
include_once '../../bootstrap.php'; 
header('Content-Type: application/json');//return json header 

    $username = $_SESSION['username']; 
    $tweets = Tweet::loadAllTweets($connection); 
    $jsonTweets = []; 


foreach ($tweets as $tweet) { 
    $jsonTweets[] = json_decode(json_encode($tweet), true); 
} 

$response = ["tweets" => $jsonTweets, 
      "success" => $username]; 

echo json_encode($response); 

AJAX

$.ajax({ 
     url: "../admin/ajax/mainpage.php", 
     dataType: 'json' 
    }) 
     .done(function (response) { 
      console.log(response.tweets); 
     }) 
     .fail(function (response) { 
      console.log(response); 
     }); 

什麼我做錯了,非常感謝任何見解。

+0

'Tweet'類怎麼樣? –

+0

我已經添加了整個Tweet類。 – oompaloompa

回答

2

Tweet類的私有屬性對json_encode不可見,因此不包含在json中。將它們公開爲實施\JsonSerializable並使用自定義jsonSerialize實現,例如,

class Tweet implements \JsonSerializable 
{ 
    // ... 

     public function jsonSerialize() 
     { 
      return [ 
       'foo' => $this->foo, 
       'bar' => $this->bar 
      ]; 
     } 
} 

更多的可視性:http://docs.php.net/language.oop5.visibility 不那麼明顯的事情是,你的靜態方法loadTweetData確實可以訪問專用道具,因爲對象是同一類的。

註銷主題:讓您的Tweet模型擴展用戶有點尷尬,因爲Tweet不是用戶(違反Liskov substitution principle)。