将带有$ _SESSION值的记录写入数据库表

时间:2013-04-09 11:43:23

标签: php mysql session record

我似乎无法将我的$ _SESSION变量的值写入我的数据库表的记录中,该记录具有自动递增的主键。我在论坛上找了很多地方,但找不到我的问题的解决方案。我的预感是我需要为自动增量添加一些工作,但我不确定。我正在使用的代码如下所示。我做错了什么?

<?php

// SESSION FILE
include ("sessionstart.inc");

echo "<html>
    <head><title>Reports-SESSION</title></head>
    <body>";

include ("misc.inc"); //THIS SETS $cxn AS MY VARIABLE TO CONNECT TO THE DATABASE

// SELECT THE DATABASE TO USE
mysqli_select_db($cxn,"carregistration") or die(mysqli_error($cxn));

// SET TEST VALUES IN $_SESSION VARIABLE
$_SESSION['OwnerCarIdentifier']='6Gh7J8';
$_SESSION['CarType']='station car';

// TEST TO SEE WHAT VALUES ARE NOW IN $_SESSION
foreach ($_SESSION as $field => $value)
{
    echo "$field = $value<br />\n";
}
// THIS CONFIRMS THAT THE TWO $_SESSION VALUES ARE THERE AND AS SET ABOVE

echo "<br />";

// NOW WRITE VALUES FROM $_SESSION INTO A NEW RECORD IN THE DATABASE
mysqli_query($cxn,"INSERT INTO 'car' (OwnerCarIdentifier,CarType) VALUES ('$_SESSION[OwnerCarIdentifier]','$_SESSION[CarType]')");

//ERROR CHECKING TO SEE IF THE DATA WERE SUCCESSFULLY RECEIVED BY THE DATABASE OR NOT.
if (mysqli_connect_errno()) {
echo "The connection with the database failed." . mysqli_connect_error();
exit();
}

// CLOSE THE RECORD
mysqli_close($cxn);

//DESTROY THE SESSION: THIS STATEMENT SHOULD APPEAR AT THE VERY END WHEN YOU HAVE STORED ALL THE FIELDS FOR A ROW IN THE DATABASE
session_destroy();


?>
</body>
</html>

4 个答案:

答案 0 :(得分:1)

首先....

 mysqli_query($cxn,"INSERT INTO `car` (`OwnerCarIdentifier`, `CarType`) VALUES ('" .$_SESSION['OwnerCarIdentifier']."','".$_SESSION['CarType']."')");

第二......我希望db中的主键不是OwnerCarIdentifier,因为你不能在字符串上放一个自动增量。

第三......希望数据不会从某个表单或某个东西进入会话,或者你有一个巨大的mysql注入。

答案 1 :(得分:1)

试试这个。

mysqli_query($cxn,"INSERT INTO 'car' (`OwnerCarIdentifier`,`CarType`) VALUES ('".$_SESSION['OwnerCarIdentifier']."','".$_SESSION['CarType']."')");

这将正确执行。

答案 2 :(得分:1)

试试这个:

$sql = mysql_query("INSERT INTO car VALUES('{$_SESSION['OwnerCarIdentifier']}','{$_SESSION['CarType']}' ");

它对我有用。

答案 3 :(得分:0)

另一种方式:

     $sql = mysqli_query($cxn,"INSERT INTO 'car' (OwnerCarIdentifier,CarType) VALUES ('{$_SESSION[OwnerCarIdentifier]}','{$_SESSION[CarType]}')");

     if(mysqli_affected_rows($cxn) === 0)
     {
        eixt ("Error on insert");
     }