MySQL + PHP:使用外键获取数据

时间:2010-08-15 20:08:53

标签: php mysql foreign-keys

我有2个表(用户,墙)。 Wall表中的UserID是外键。我将如何使用此获取用户详细信息? (我想获取发布消息的用户Forename和Surname。)

用户表: alt text http://i33.tinypic.com/1eq6n5.png

挂表: alt text http://i37.tinypic.com/b5po5u.png

编辑:我无法弄清楚如何显示数据。

<?php include('config.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
    <head>
        <title>Alpha</title>
        <link rel="stylesheet" href="style.css" type="text/css" />  
    </head>
    <body>

<?php 

// Logged IN
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Email'])) {


// Post to Database
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string($_POST['message']);
$postmessage = mysql_query("INSERT INTO Wall (Message, UserID) VALUES('".$message."', '".$_SESSION['UserID']."')");
}

// Collet Latest Posts

$result = mysql_query('SELECT Message, UserID 
                         FROM Wall 
                     ORDER BY MessageID DESC 
                        LIMIT 20') or die('Invalid query: ' . mysql_error());

// Collet Post User

$query = mysql_query('SELECT Forename, Surname FROM Users INNER JOIN Wall ON Users.UserID = Wall.UserID;') or die('Invalid query: ' . mysql_error());

    ?>
    <div id ="container">
        <div id="insideleft">
            <ul>
                <li><a href="index.php">Home</a></li>
                <li><a href="profile.php">Edit Profile</a></li>
                <li><a href="wall.php">Community Wall</a></li>
                <li><a href="logout.php">Logout</a></li>
            </ul>
        </div>
        <div id="insideright">
            <h1>Community Wall</h1>
            <br />
            <form method="post" action="wall.php" name="wallpost" id="wallpost">
                <label for="message" class="message">Message: </label> <input type="text" name="message" id="message" class="message"/>
                <input type="submit" name="messagesub" id="messagesub" value="Post" /><br /><br />
                </fieldset>
            </form>
            <?php while ($row = mysql_fetch_assoc($result)) { ?>
            <p></p>
            <p><?=stripslashes($row['Message'])?></p><br />

<?php
} ?>

        </div>
    </div>
    <?php
}

//else {echo "<meta http-equiv='refresh' content='0;index.php'>";}

?>
</body>
</html>

正如您所看到的,我正在输出消息,但我不知道如何输出海报的Forename和Surname。

4 个答案:

答案 0 :(得分:8)

$hostname = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'database';

$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

$query = <<<QUERY
    SELECT Forename, Surname 
    FROM Users
    INNER JOIN Wall ON Users.UserID = Wall.UserID;
QUERY;

$statement = $db->query($query);
$rows = $statement->fetch(PDO::FETCH_ASSOC);
print_r($rows);

$db = null;

修改 鉴于新信息,您应该将您的查询合并为一个。

<?php include('config.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
    <head>
        <title>Alpha</title>
        <link rel="stylesheet" href="style.css" type="text/css" />  
    </head>
    <body>

<?php 

// Logged IN
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Email'])) {


// Post to Database
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string($_POST['message']);
$postmessage = mysql_query("INSERT INTO Wall (Message, UserID) VALUES('".$message."', '".$_SESSION['UserID']."')");
}

// Collet Latest Posts

$query = <<<QUERY
    SELECT Users.UserID, Message, Forename, Surname 
    FROM Users
    INNER JOIN Wall ON Users.UserID = Wall.UserID;
    ORDER BY MessageID DESC
    LIMIT 20;
QUERY;
$result = mysql_query($query) or die('Invalid query: ' . mysql_error());

// Collet Post User
    ?>
    <div id ="container">
        <div id="insideleft">
            <ul>
                <li><a href="index.php">Home</a></li>
                <li><a href="profile.php">Edit Profile</a></li>
                <li><a href="wall.php">Community Wall</a></li>
                <li><a href="logout.php">Logout</a></li>
            </ul>
        </div>
        <div id="insideright">
            <h1>Community Wall</h1>
            <br />
            <form method="post" action="wall.php" name="wallpost" id="wallpost">
                <label for="message" class="message">Message: </label> <input type="text" name="message" id="message" class="message"/>
                <input type="submit" name="messagesub" id="messagesub" value="Post" /><br /><br />
                </fieldset>
            </form>
            <?php while ($row = mysql_fetch_assoc($result)) { ?>
            <p></p>
            <p>

            <?php
              echo "Message: ".stripslashes($row['Message'])."<br />";
              echo "Name: {$row['Surname']}, {$row['Forename']}";
            ?>

            </p><br />

<?php
} ?>

        </div>
    </div>
    <?php
}

//else {echo "<meta http-equiv='refresh' content='0;index.php'>";}

?>
</body>
</html>

答案 1 :(得分:1)

在这里,主要目标是您在sql查询中首先写入带消息的表的消息,在您的示例中,Wall表和查询可以如下所示: $result = mysql_query ("SELECT u.Forename, u.Surname, w.Message FROM Wall AS w INNER JOIN Users AS u ON(w.UserID=u.UserID)");

现在输出使用时:

<p><?=stripslashes($row['Surname'])?></p><br />
<p><?=stripslashes($row['Lastname'])?></p><br />
<p><?=stripslashes($row['Message'])?></p><br />

当然要做正确的格式化。

答案 2 :(得分:0)

select w.MessageID, w.Message, u.UserID, u.Forename, u.Surname
from Wall w
inner join Users u on w.UserID = u.UserID

答案 3 :(得分:0)

或者以另一种形式:

SELECT w.*, u.Forename, u.Surname
FROM Wall w, Users u
WHERE w.UserID=u.UserID