我有使用mySQL將公告發布到數據庫的php腳本。我想將其更改爲使用PDO。如何將mySQL轉換爲PDO
我原來的代碼是在這裏:
<?php
require_once"connection.php";
session_start();
if(isset($_POST['annForm']))
{
$userID=$_SESSION['sessionUser'];
$idQuery=mysql_query("SELECT adminID FROM administrator WHERE username='$userID'");
$adminID=mysql_fetch_array($idQuery);
$genAnnouncement=$_POST['annForm'];
$genAnnouncement=mysql_real_escape_string($genAnnouncement);
$addGenAnnQuery="INSERT INTO generalannouncement (adminID, genAnnouncement) VALUES('$adminID[0]','$genAnnouncement')";
$announcementAdded=mysql_query($addGenAnnQuery);
if(!$announcementAdded)
{
echo 'Could Not Add Announcement, Try Again Later.<br>';
echo mysql_error();
}
else
echo 'Announcement Added Successfully.<br>';
header("refresh:500;url=adminsHomepage.php");
return;
mysql_close($con);
}
?>
我已經修改使用PDO,但我得到現在與不確定的指數$ adminID [0]和線25完整性約束線24個錯誤代碼違規:1048'adminID'列不能爲空。修改後的代碼如下:
require_once"connection.php";
session_start();
if(isset($_POST['annForm']))
{
$userID=$_SESSION['sessionUser'];
$idQuery= $conn->prepare("SELECT adminID FROM administrator WHERE username='$userID'");
$idQuery->execute();
$adminID= $idQuery->fetch();
$genAnnouncement=$_POST['annForm'];
if (isset($genAnnouncement))
{
$sql = "INSERT INTO generalannouncement (adminID, genAnnouncement)
VALUES (:adminID, :genAnnouncement)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(
':adminID' => $_POST['$adminID[0]'],
':genAnnouncement' => $_POST['annForm']));
echo 'Announcement Added Successfully.<br>';
header("refresh:500; url= adminsHomepage.php");
return;
}}
爲什麼你'$ adminID [0]'在你的原始代碼中,但是在你的新代碼中將它包裝在'$ _POST' - >'$ _POST ['$ adminID [0]']'中? – Sean
它應該只是':adminID'=> $ adminID [0],'沒有'$ _POST [''/'']' – Sean
@Sean我有$ adminID [0],因爲那是ID的vaue當前用戶登錄 – user3531869