1

我似乎无法将 $_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

4 回答 4

1

尝试这个:

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

它对我有用。

于 2013-11-26T13:12:38.547 回答
1

第一的....

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

其次...我希望您在 db 中的主键不是OwnerCarIdentifier因为您不能在字符串上放置自动增量。

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

于 2013-04-09T11:48:06.987 回答
1

尝试这个。

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

这将正确执行。

于 2013-04-09T11:48:27.540 回答
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");
     }
于 2013-11-26T13:18:43.897 回答