如何从多个表中选择

时间:2015-02-16 21:27:49

标签: php mysql select

id  friend1 friend2
1   obi      ezenwa
2   obi      obinna
3   obi      ezenwa

这是我如何从上表中选择朋友列表

<?php

require("config.inc.php");

if (!empty($_POST)) {
$query = "SELECT users.* FROM users WHERE users.username IN 
(SELECT friend2 FROM friends where friend1=:username
UNION
SELECT
friend1 FROM friends where friend2=:username)";

    $query_params = array(
        ':username' => $_POST['username']
    );


try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));
}
$rows = $stmt->fetchAll();


if ($rows) {
    $response["success"] = 1;
    $response["message"] = "Post Available!";
    $response["posts"]   = array();

    foreach ($rows as $row) {
        $post             = array();

        $post["TAG_NAME"]    = $row["username"];

        array_push($response["posts"], $post);
    }

    echo json_encode($response);


} else {
    $response["success"] = 0;
    $response["message"] = "No Post Available!";
    die(json_encode($response));
}

} else {
?>
        <h1>Login</h1> 
        <form action="selectfriends.php" method="post"> 
            Username:<br /> 
            <input type="text" name="username" placeholder="username" /> 
            <br /><br /> 

            <input type="submit" value="Login" /> 
        </form> 
        <a href="register.php">Register</a>
    <?php
}

?> 

它运作良好我也有一个像下面这个名为chatt的表。保存用户的消息。

                              Chatt
      fromm     too       message           time
        obi2    ezenwa  this is me yes  2015-02-08 23:47:31
        obi     ezenwa  ok i can see    2015-02-08 23:47:31
        obi     ezenwa  seems good      2015-02-12 17:44:10
        ezenwa  obi     i agree         2015-02-12 17:49:16
        obi     ezenwa  j man           2015-02-13 14:42:16
        obi     ezenwa  j man           2015-02-13 14:43:28
        obi2    ezenwa  this is cool    2015-02-13 14:58:28

我想显示已输入的用户名和$ row中包含的所有朋友之间的最后一条消息[&#34;用户名&#34;] ...我只想要朋友的用户列表和他们之间的最后一条消息就像blackberry messenger和WhatsApp ....

0 个答案:

没有答案