无法从SESSION变量和查询数据库中读取值

时间:2014-12-17 18:46:06

标签: php session

我无法获取会话变量的值以将其插入到我的数据库中。 lat和lng是双打     

$lat = mysql_real_escape_string($lat);
$lng = mysql_real_escape_string($lng);


$sql="INSERT INTO POINT (LocationLat,LocationLngme,UserName) VALUES (&lat,&lng,$usr)";
mysql_query($sql);

?>

2 个答案:

答案 0 :(得分:6)

session_start() 必须位于您希望使用会话的任何页面的顶部:

<?php
session_start();
$lat = $_REQUEST['lat'];
$lng = $_REQUEST['lng'];
$usr = "'".echo $_SESSION['username']."'";

$lat = mysql_real_escape_string($lat);
$lng = mysql_real_escape_string($lng);


$sql="INSERT INTO POINT (LocationLat,LocationLngme,UserName) VALUES ('&lat','&lng','$usr')";
mysql_query($sql);

?>

仅供参考,您的查询中的字符串值缺少引号。

And please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

您也对SQL injections

持开放态度

答案 1 :(得分:0)

@Jonh Conde的答案可能对你有用,但最好做到以下几点:

<?php
session_start();
$lat = mysql_real_escape_string( trim( $_REQUEST['lat'] ) );
$lng = mysql_real_escape_string( trim( $_REQUEST['lng'] ) );
$usr = mysql_real_escape_string( trim( $_SESSION['username'] ) );

$sql="INSERT INTO `POINT` (`LocationLat`, `LocationLngme`, `UserName`) VALUES ('$lat', '$lng', '$usr')"; 
// Putting '`' backticks around column and table names makes sure some mysql errors are prefented.
mysql_query($sql);

?>

mysqli_*被删除后,请查看PDOmysql_*