添加MySQL查询的链接

时间:2014-05-02 13:22:00

标签: php mysql

嗨,我是PHP& MySQL和我正在尝试为作业编写日记页面,但我不确定如何将查询链接到显示已单击的完整查询的另一个页面。基本上,用户可以访问他们以前的日记帐分录。下面是我到目前为止编写的代码:

<?php
session_start();
if(isset($_SESSION['uname'])){
echo "Welcome " . $_SESSION['uname'];
}
require_once 'PHP/Constants.php';
$conn = new MySQLi(DB_SERVER, DB_USER, DB_PASSWORD,DB_NAME) or die ('There was a problem connecting to the database');
$uname = $_SESSION['uname'];
$query="SELECT Username, Date_Created, Title FROM journal";
$result=mysqli_query($conn, $query);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Journal</title>
</head>

<body>
<p>
<h1>My Journal</h1>
</p>
    <?php
        echo "<table width='400' border='1' cellspacing='0' cellpadding='3'>
            <tr>
            <th>Date</th>
            <th>Title</th>
            </tr>";
            while ($rows=mysqli_fetch_array($result)){
                if($rows['Username']=$uname) {
                    echo "<tr>";
                    echo "<td>" . $rows['Date_Created'] . "</td>";
                    echo "<td>" . $rows['Title'] . "</td>";
                    echo "</tr>"; 
                } else echo "No Journal Entries Found";
            }
        echo "</table>";
    ?>
    </table>    
<form method="post" action="new_entry.php">
    <p>
        <input type="submit" id="new_entry" value="New Entry" name="new_entry" />
    </p>
</form>
<form method="post" action="choices.php">
    <p>
        <input type="submit" id="back" value="Back" name="back" />
    </p>
</form>
</body>
</html>

提前感谢您的帮助 - 尼克

1 个答案:

答案 0 :(得分:0)

首先,您必须在表中包含ID或唯一列,在这种情况下,假设UserName是唯一的。所以你打印到另一个php文件的链接并通过GET发送该参数:

while ($rows=mysqli_fetch_array($result)){
    if($rows['Username']==$uname) {
        echo "<tr>";
        echo "<td>" . $rows['Date_Created'] . "</td>";
        echo "<td>" . $rows['Title'] . "</td>";
        echo "<td><a href='info.php?username=".$rows['Username']."'>Link</a></td>";
        echo "</tr>"; 
    } else 
         echo "No Journal Entries Found";
    }
}

现在在info.php中,您将使用给定的用户名重新获取值并查询数据库:

<?php
$username = $_GET['username'];
// Escape value to prevent SQL injection
...
$query="SELECT * FROM journal WHERE UserName = '".$username."'";
// And then display the info as you want
...

希望这对你有所帮助。