I have this php script for posting announcements to a database using mySQL. I'd like to change it to use PDO.
The code I have originally is here:
<?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);
}
?>
I have modified the code to use PDO but I am getting errors now on line 24 with undefined index $adminID[0] and line 25 with Integrity constraint violation: 1048 Column 'adminID' cannot be null. The modified code is as follows:
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;
}}