2016-03-20 87 views
0

我有使用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; 
}} 
+0

爲什麼你'$ adminID [0]'在你的原始代碼中,但是在你的新代碼中將它包裝在'$ _POST' - >'$ _POST ['$ adminID [0]']'中? – Sean

+0

它應該只是':adminID'=> $ adminID [0],'沒有'$ _POST [''/'']' – Sean

+0

@Sean我有$ adminID [0],因爲那是ID的vaue當前用戶登錄 – user3531869

回答

3

在原來的MySQL_查詢您有:

$addGenAnnQuery = " 
     INSERT INTO generalannouncement 
        (adminID, genAnnouncement) 
      VALUES ('$adminID[0]','$genAnnouncement') 
"; 

所以,如果你的舊的查詢工作,新execute必須是這樣的:

$stmt->execute(array(
    ':adminID' => $adminID[0], 
    ':genAnnouncement' => $genAnnouncement)); 
+0

謝謝。現在確實能正常工作 – user3531869

2

我想,你在這裏有問題:$_POST['$adminID[0]'] 只是嘗試刪除撇號。

+0

謝謝。我已經刪除了撇號,但現在它在同一行上顯示「Undefined index:Adm101」,並且在它下面的行中有一個錯誤,表示管理員ID不能爲空,完整性約束 – user3531869

+0

這不僅僅是需要刪除的撇號,而是包裝'$ adminID [0]'的整個'$ _POST [''/'']''。 – Sean