如何从MYSQL本地数据库获取用户信息

时间:2015-07-08 23:59:25

标签: php

嘿,我需要从数据库中获取信息并将其显示在index.php上。

<html>
<body>
<?php
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('users');

$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);

echo "<table>"; // start a table tag in the HTML

while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";  //$row['index'] the index here is a field name
}

echo "</table>"; //Close the table in HTML

mysql_close(); //Make sure to close out the database connection
?>
</body>
</html>

然而,这将显示数据库中所有用户的信息。 我在数据库中有一个主键,即帐号,我们可以使用它只在页面上显示有关该帐户的信息吗? 我还需要将详细信息保存到php页面上的变量中,这样做一些指导就可以了。

谢谢奥利弗

3 个答案:

答案 0 :(得分:0)

为了根据特定用户检索数据,您必须明确告诉mysql。所以,添加WHERE id = {我想要你的信息}。

第二个问题。 “当用户登录时,你如何获得id。”

答案是你可以(a)如何在登录时初始化会话或(b)如何在脚本中使用Id来运行查询用户名的另一个文件甚至循环如何然后你得到Id。

选项b的缺点是你正在减慢这一步,并且正在做很多可能导致整个网站崩溃的电话。

您可以选择如何为用户获取特定内容。

答案 1 :(得分:0)

<?php
include('session.php');
?>
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'root', 'Oliver'); //The Blank string is the password
mysql_select_db('users');

$query = "SELECT * FROM username WHERE username='$login_session'"; //You don't need a ; like you do in SQL
$result = mysql_query($query);

echo "<table>"; // start a table tag in the HTML

while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['username'] . "</td></tr>";  //$row['index'] the index here is a field name
echo "<tr><td>" . $row['sex'] . "</td><td>" . $row['phone'] . "</td></tr>";  //$row['index'] the index here is a field name
echo "<tr><td>" . $row['email'] . "</td><td>" . $row['password'] . "</td></tr>";  //$row['index'] the index here is a field name
}

echo "</table>"; //Close the table in HTML

mysql_close(); //Make sure to close out the database connection
?>
</body>
</html>

我得到了WHERE username =“$ login_session” login_session值是数据库中每个用户的唯一值,因此它永远不会相同,所以我可以使用它来仅为该用户提取信息

答案 2 :(得分:0)

您可以使用会话变量来存储您正在使用会话的情况下的信息,如果没有,您可以使用常规变量来存储信息,也可以使用post或get变量