我已设法使用登录表单中的用户名创建cookie,但是如何将db查询中的用户ID也添加到cookie中?
这就是我现在所拥有的
<?php
include 'connection.php';
// 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");
// username and password sent from form
$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){
setcookie("user", $myusername, time()+3600);
header("location:index.php");
}
else {
echo "Wrong Username or Password";
}
?>
答案 0 :(得分:0)
使用$_SESSION
更容易。
在要使用会话变量的每个页面的顶部添加session_start();
。之后,您可以设置和获取与任何普通数组一样的会话变量。例如:
<?php
session_start();
$_SESSION['loggedIn'] = true;
$_SESSION['userId'] = 5;
?>
在另一页上:
<?php
session_start();
echo $_SESSION['loggedIn']; //will contain true
echo $_SESSION['userId'] = 5; //will contain 5
?>
答案 1 :(得分:0)
试试这个。
<?php
ob_start();
include 'connection.php';
// 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");
// username and password sent from form
$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){
$users = mysql_fetch_array($result);
# pass the user ID column name as array key of `$users`
setcookie("userID", $users['user_id'], time()+3600);
header("location:index.php");
ob_clean();
}
else {
echo "Wrong Username or Password";
}
?>
答案 2 :(得分:0)
$Rows=mysql_fetch_array($result);
// Assuming that the column name in the DB is user_id then you can get the user_id using : $Rows['user_id']
// so you can store the cookie in this way:
setcookie("user_id", $Rows['user_id'], time()+3600);