0

即使用户未登录,我也需要显示用户从 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 编码的新手。请帮助我。

4

2 回答 2

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";
}
于 2012-07-08T04:17:24.827 回答
0

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

我能想到的唯一方法是在创建帐户时存储用户 IP,并在任何人访问该页面时读取 IP。如果匹配用户,则显示信息。但是,这样做时您可能会冒一些安全措施的风险,并且当 IP 更改时,这可能会在将来以这种方式搞砸事情。

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

于 2012-07-08T21:32:44.107 回答