当 MySQL 表中的“用户”“登录”时,我正在尝试使用 php 脚本仅显示链接。我试过的 php 代码有什么问题?我的在下面:
<?
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
<html>
<head>
require_once(checklogin.php)
</head>
<body>
<?php
if($myusername == "admin");
echo "<a href="test.html"> Click Me! </a>";
?>
</body>
</html>
$myusername 变量来自下面的文件,该文件根据 mysql 表检查表单(在另一个页面上)的用户名并打开一个 session 。
<?php
ob_start();
$host="-----";// Mysql username
$password="-----"; // Mysql password
$db_name="-------"; // Database name
$tbl_name="-------"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>
所以重复我的问题:这段代码到底出了什么问题
if($myusername == "admin");
echo "<a href="test.html"> Click Me! </a>";
?>
应该识别用户并显示链接
最佳答案
语法错误的原因是 if
语句之后的杂散 ;
。它应该被删除。
if($myusername == "admin");
//-----------------------^^
// Error here -- remove that semicolon!
这里还有一些其他的问题,比如session_register()
中没有引号的值,应该用引号括起来:
session_start();
if(!session_is_registered(myusername)){
//-----------------------^^^^^^^^^^^^^
header("location:main_login.php");
}
但是,不推荐使用session_register()
。设置 session 变量的正确现代方法是使用 $_SESSION
超全局数组。 (参见 deprecation notices in the PHP docs)
// Set a variable
session_start();
$myusername = "admin";
$_SESSION['myusername'] = $myusername;
// Get a variable
// Always call session_start() at the beginning of the script
echo $_SESSION['myusername'];
// admin
关于PHP 和 MySQL 仅在特定条件下回显字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9527729/