PhP会话传递并组合变量和字符串

时间:2014-03-17 02:28:38

标签: php mysql session

我的登录代码:

<?php
session_start();
$f_usr= $_POST["userid"];
$f_pswd= $_POST["password"];
$_SESSION['user']=$f_usr;
$con=mysql_connect("localhost","root","");
if(! $con)
{
        die('Connection Failed'.mysql_error());
}
mysql_select_db("finaltest",$con);
$result=mysql_query("select * from user");
while($row=mysql_fetch_array($result))
{
    if($row["username"]==$f_usr && $row["password"]==$f_pswd)
        header('Location: selectdata.php');
    else
        echo"Sorry : $f_usr";
}
?>

selectdata.php

<?php
session_start();
$s= $_SESSION['user'];
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("finaltest") or die(mysql_error());
$select="temperature".$s;
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM $select") 
or die(mysql_error());  

echo "<table border='1'>";
echo "<tr> <th>username</th> <th>password</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
    // Print out the contents of each row into a table
    echo "<tr><td>"; 
    echo $row['username'];
    echo "</td><td>"; 
    echo $row['password'];
    echo "</td></tr>"; 
} 

echo "</table>";
?>

实际上会话varibale没有被解析我收到错误:

Notice: Undefined index: user in C:\xampp\htdocs\bars\selectdata.php on line 3

我有另一个问题我想选择一个名为“temperaturexyz”的数据库,其中我想要存储在字符串中的温度,而xyz是我通过会话得到的变量我想要将两者结合起来以便我可以得到我可以在查询中使用的变量

1 个答案:

答案 0 :(得分:0)

关于您的会话:您尝试在登录代码中设置的会话变量$_SESSION['user']未按预期正确设置变量。 尝试:

<?php
 session_start();
 $f_usr= $_POST["userid"];
$f_pswd= $_POST["password"];
$_SESSION['user']=$f_usr;
echo $_SESSION['user'] //<-------- see if this echo's out the value you are expecting

至于你的变量: 我假设你的意思是你想要一个变量名$ thermxyz,但你是动态创建变量名。所以

$select="temperature".$s;
$$select = /* Insert whatever value you need here*/ //<-- you can then call this variable like this (ie. $temperaturexyz)