我已經將PHP代碼插入到前一頁的HTML表單數據到數據庫中,並在同一個SQL語句中從插入的數據返回PostID。 PostID列是AUTO_INCREMENTING。我現在一直在研究這個問題一兩個星期,但沒有找到重要的解決方案。爲什麼INSERT INTO後跟SELECT LAST_INSERT_ID()不輸出任何內容?
<?php
include("dbconnect.php");
mysql_select_db("astral_database", $con);
session_start();
$username = $_SESSION['username'];
$forumtext = $_POST["forumtext"];
$forumsubject = $_POST["forumsubject"];
$postquery = 'INSERT INTO Forums (Creator, Subject, Content) VALUES ("$username", "$forumsubject", "$forumtext"); SELECT LAST_INSERT_ID()';
$result = mysql_query($postquery, $con);
if (!$con) {
echo "<b>If you are seeing this, please send the information below to [email protected]</b><br>Error (331: dbconnect experienced fatal errors while attempting to connect)";
die();
}
if ($username == null) {
echo "<b>If you are seeing this, please send the information below to [email protected]</b><br>Error (332: Username was not specified while attempting to send request)";
die();
}
if ($result != null) {
echo "last id: " . $result;
$fhandle = fopen("recentposts.txt", "r+");
$contents = file_get_contents("recentposts.txt");
fwrite($fhandle, json_encode(array("postid" => $result, "creator" => $username, "subject" => $forumsubject, "activity" => time())) . "\n" . $contents);
fclose($fhandle);
mysql_close($con);
header("location: http://astraldevgroup.com/forums");
die();
} else {
die("<b>If you are seeing this, please send the information below to [email protected]</b><br>Error (330: Unhandled exception occured while posting forum to website.)<br>");
echo mysql_error();
}
mysql_close($con);
?>
首先,mysql_query不會從SELECT語句返回任何內容。我還沒有找到任何能在同一個查詢中正確運行SELECT語句和INSERT語句的東西。如果我嘗試在兩個不同的語句中運行它們,它仍然不會返回任何內容。我試着在SQL控制檯中運行下面的語句,它運行得很好,沒有錯誤。
INSERT INTO Forums (Creator, Subject, Content) VALUES ("Admin", "Test forum 15", "This is a forum that should give me the post id."); SELECT LAST_INSERT_ID();
首先,您必須避免在查詢中使用mysql_,因爲它被聲明爲不安全。 – ameenulla0007
[您的腳本存在SQL注入攻擊風險。](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) –
請[停止使用'mysql_ * '函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。 [這些擴展](http://php.net/manual/en/migration70.removed-exts-sapis.php)已在PHP 7中刪除。瞭解[編寫](http://en.wikipedia.org/ wiki/Prepared_statement)語句[PDO](http://php.net/manual/en/pdo.prepared-statements.php)和[MySQLi](http://php.net/manual/en/mysqli.quickstart .prepared-statements.php)並考慮使用PDO,[這真的很簡單](http://jayblanchard.net/demystifying_php_pdo.html)。 –