显示db中的值,无需在php中登录

时间:2012-07-07 13:26:08

标签: php

即使用户未登录,我也需要显示用户从db创建的内容。

<? php

$get_user_content = mysqli_query($conn, "SELECT * FROM content WHERE UserName = '$username'") or die($dataaccess_error);

if(mysqli_num_rows($get_user_content) == 1 )
{
  $row = mysqli_fetch_array($get_user_content);

  $title = $row['utitle'];
  $content = $row['ucontent'];
}

echo $title;
echo $content;

?>

但我收到两个错误:

undefined variable: username

Warning: mysqli_query() expects parameter 1 to be mysqli

我是PHP编码的新手。请帮帮我。

2 个答案:

答案 0 :(得分:1)

您需要定义用户名变量,您还需要连接到数据库。 如果您打算使用mysqli,那么最好使用面向对象的样式。 Mysqli可能不是理想的解决方案,请参阅此处的Cletus答案:MySQL vs MySQLi when using PHP

您需要在php.net上查看php指南以了解该语言,并确保查看评论。你也可以谷歌教程。如果全部失败,那么stackoverflow将成为获得帮助的地方。

<?php
$username = trim($_POST['username']); //where username is a form field sent using post method, we trim it to remove white spaces so if user just enters spaces, the script will see it as empty string.

//Connect to database  http://www.php.net/manual/en/mysqli.query.php
$conn = mysqli_connect("localhost", "my_user", "my_password", "yourdatabasename");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}


if ($username){
    $username=mysqli_real_escape_string($conn, $username); //escape the string AFTER you connect http://www.php.net/manual/en/mysqli.real-escape-string.php
    $get_user_content = mysqli_query($conn, "SELECT * FROM content WHERE UserName =    '$username' LIMIT 1") or die(mysqli_error($conn));  //assuming you have table called content with a field called UserName to store the username, add limit 1 since you only need one anyway.  , where does databaseaccess_error comes from? it's undefined. use mysqli_error

   if(mysqli_num_rows($get_user_content) == 1 )
   {
       $row = mysqli_fetch_array($get_user_content);

       $title = $row['utitle'];
       $content = $row['ucontent'];


       echo $title;
       echo $content;
   }else echo "User couldn't be found";
}

答案 1 :(得分:0)

如果您正在显示用户创建的信息,则很难在用户未登录的情况下显示该信息。

我能想到的唯一方法是在创建帐户时存储用户IP,并在有人访问该页面时阅读IP。如果它与用户匹配,则显示信息。虽然这样做可能会冒一些安全措施的风险,但是当IP发生变化时,这可能会在未来以这种方式搞乱。

要说清楚,您想要在访问页面时显示在您的网站上创建的内容,但是我没有登录?或者只是任何用户创建的东西?