未定义用户 ID
Posted
技术标签:
【中文标题】未定义用户 ID【英文标题】:The user ID is not defined 【发布时间】:2014-06-27 15:31:23 【问题描述】:好的,我正在尝试列出 mysql 中的所有用户,这可以正常工作,但是当我添加 profile.php?id=
时,我得到了我的 else 代码 。我如何设置它,所以它不会说用户 ID 未定义。这是我的代码:
<?php
include('config/db.php');
?>
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="password"; // Mysql password
$db_name="login"; // Database name
$tbl_name="users"; // Table name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//We check if the members ID is defined
if(isset($_GET['user_id']))
$id = intval($_GET['user_id']);
//We check if the user exists
$dn = mysql_query('select user_name, user_email from users where user_id="'.$id.'"');
if(mysql_num_rows($dn)>0)
$dnn = mysql_fetch_array($dn);
//We display the user datas
?>
This is the profile of "<?php echo htmlentities($dnn['user_name']); ?>" :
<table style="width:500px;">
<tr>
<td><?php
if($dnn['avatar']!='')
echo '<img src="'.htmlentities($dnn['avatar'], ENT_QUOTES, 'UTF-8').'" style="max-width:100px;max-height:100px;" />';
else
echo 'This user dont have an avatar.';
?></td>
<td class="left"><h1><?php echo htmlentities($dnn['user_name'], ENT_QUOTES, 'UTF- 8'); ?></h1>
Email: <?php echo htmlentities($dnn['user_email'], ENT_QUOTES, 'UTF-8'); ?><br />
This user joined the website on <?php echo date('Y/m/d',$dnn['signup_date']); ?> </td>
</tr>
</table>
<?php
else
echo 'This user dont exists.';
else
echo 'The user ID is not defined.';
?>
this is the users.php
<?php
//We get the IDs, usernames and emails of members
$req = mysql_query('SELECT `user_id`, `user_name`, `user_email`, `user_sign_up_date` FROM `users`');
while($dnn = mysql_fetch_array($req))
?>
<tr>
<td class="left"><?php echo $dnn['user_id']; ?></td>
<td class="left"><a href="profile.php?<?php echo $dnn['user_id']; ?>"><?php echo ($dnn['user_name']); ?></a></td>
<td class="left"><?php echo($dnn['user_email']); ?></td>
</tr>
<?php
?>
【问题讨论】:
"profile.php?id
=" 而你正在使用where user_id
- ahem
Please, don't use mysql_*
functions in new code。它们不再维护and are officially deprecated。看到red box?改为了解prepared statements,并使用PDO 或MySQLi - this article 将帮助您决定哪个。如果你选择 PDO,here is a good tutorial.
在我的数据库中,id 名称是 user_id,我删除了 mysql 函数,但仍然收到错误。
您需要根据您的列名使用profile.php?user_id
而不是profile.php?id
和$id = intval($_GET['user_id']);
好的,我明白了,但我仍然收到错误她是用户列表 您的查询在以下行返回 false
$dn = mysql_query('select user_name, user_email from users where user_id="'.$id.'"');
你需要找出原因,在它返回 true 之前你不应该尝试任何事情:
$sql = sprintf("SELECT user_name, user_email FROM users WHERE user_id = %s",
mysql_real_escape_string($id));
$dn = mysql_query($sql);
if(!$dn)
echo "mysql_query() failed";
exit();
【讨论】:
以上是关于未定义用户 ID的主要内容,如果未能解决你的问题,请参考以下文章