我有以下一点PHP应该从表单中读取条目然后更新相应的数据表以及附加登录用户的用户名,但由于某种原因我们的数据库没有更新。 / p>
$Date = $_POST["Date"];
$Description = $_POST["Description"];
$Hour = (float)$_POST["Lat"];
$Min = (float)$_POST["Lon"];
$Username = $_SESSION['username'];
mysql_connect("localhost", "dbusername", "dbpass");
mysql_select_db("dbname",$connect) or die( "Unable to select database");
$sql = ("INSERT INTO Table (Date, Description, Hour, Min, Username)
VALUES ($Date, $Description, $Lat, $Lon, $Username)");
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
echo $Date;
echo $Description;
echo $Hour;
echo $Min;
echo $Username;
提前感谢您的任何帮助
答案 0 :(得分:4)
您没有将查询输入变量括在单引号中。
$sql = ("INSERT INTO Table (Date, Description, Hour, Min, Username)
VALUES ('$Date', '$Description', '$Lat', '$Lon', '$Username')");
您在查询失败时调用mysql_error()
,可能是在第一个Date输入值附近打印了语法错误。
在将$_POST
变量传递给查询之前,您还必须使用mysql_real_escape_string()
转义,以保护自己免受SQL注入攻击。
$Date = mysql_real_escape_string($_POST["Date"]);
$Description = mysql_real_escape_string($_POST["Description"]);
// You might want to check sane bounds for these float values
// in addition to casting them as floats
$Hour = (float)$_POST["Lat"];
$Min = (float)$_POST["Lon"];
// Hopefully $Username is already sane, but escape to be safe
$Username = mysql_real_escape_string($_SESSION['username']);
调用mysql_select_db()
时,第二个参数是可选的,实际上您还没有在代码中定义$connect
。我怀疑你的意思是:
$connect = mysql_connect("localhost", "dbusername", "dbpass");
mysql_select_db("dbname",$connect) or die( "Unable to select database");
答案 1 :(得分:0)
$Hour = (float)$_POST["Lat"];
$Min = (float)$_POST["Lon"];
但是,当您编写查询时,您将这些值分别称为$ Lat和$ Lon ....
$sql = ("INSERT INTO Table (Date, Description, Hour, Min, Username)
VALUES ($Date, $Description, $Lat, $Lon, $Username)");
您发布的代码中没有任何地方您实际为$ Lat或$ Lon分配了值,但您希望将其值分配给查询的参数。实质上,您在查询中调用了不存在的变量。