开发者

Mysql trouble using $_SESSION in program

I'm trying to use $_SESSION['valid_user'] in a .php script that accesses the table "mail" under "users." $_SESSION['valid_user'] has been defined in a script which I included. Whenever I use "WHERE to=$_SESSION['valid_user']" in my SELECT statement, I get a blank page. However, if I take it out, the script runs and displays all messages in the database, not just the message that was defined to show to that par开发者_如何学Goticular username. Despite this, I can echo $_SESSION['valid_user'] outside of the while loop or SELECT statement. Here's my code:

<?php

include("mainmenu.php");

include("checklogin.php");

//$_SESSION['valid_user'] defined in checklogin.php

$con = mysql_connect("localhost", "root", "g00dfor@boy"); if(!$con){ die(mysql_error()); }

mysql_select_db("users", $con);

$result = mysql_query("SELECT * FROM mail WHERE to=$_SESSION['valid_user']");

//when executed with WHERE to=$_SESSION['valid_user'] it displays blank page.

while($row = mysql_fetch_array($result)) {

echo "To: " . $row['to'] . "| From: " . $row['from'] . "<br/>";

echo "Subject: " . $row['subject'] . "<br/><br/>" . "Message: " . $row['message'];

echo "<br/>";

}

mysql_close($con);

?>

Don't say, "Put $_SESSION['valid_user'] in double quotes." I've already tried that.


Change to $result = mysql_query("SELECT * FROM mail WHERE to='".$_SESSION['valid_user']."'");


You need to put brackets around the SESSION variable in your query.

change

$result = mysql_query("SELECT * FROM mail WHERE to=$_SESSION['valid_user']")

to

$result = mysql_query("SELECT * FROM mail WHERE to='{$_SESSION['valid_user']}'")

EDIT

You need to change

while($row = mysql_fetch_array($result))

to

while($row = mysql_fetch_assoc($result))

because you are referencing the columns by their names rather than by their index value.


Try

 $result = mysql_query("SELECT * FROM mail WHERE to='".$_SESSION['valid_user']."'");

or

 $result = mysql_query("SELECT * FROM mail WHERE to='$_SESSION[valid_user]'");

Both should not be valid queries;


Try capturing your query in a variable and printing it out to see what you get.

$query = "SELECT * FROM mail WHERE to=$_SESSION['valid_user']";

If the $_SESSION['valid_user'] contains any spaces you will need to wrap it in some form of single or double quotes other wise MySQL won't know what you really want.


Presumably user_name is a variable, originally provided by a user of your site? In that case you absolutely must escape it when embedding it in an SQL query, or you will be prone to injection attacks:

$result = mysql_query("SELECT * FROM mail WHERE to='".mysql_escape_string($_SESSION['valid_user'])."'");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜