我有这个PHP脚本,用于使用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,但我现在在第24行遇到未定义索引$ adminID [0]和第25行且出现完整性约束违规的错误: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 :(得分:3)
在原始MySQL_查询中,您有:
$addGenAnnQuery = "
INSERT INTO generalannouncement
(adminID, genAnnouncement)
VALUES ('$adminID[0]','$genAnnouncement')
";
因此,如果您的旧查询有效,则新execute
必须为:
$stmt->execute(array(
':adminID' => $adminID[0],
':genAnnouncement' => $genAnnouncement));
答案 1 :(得分:2)
我想,你这里有问题:$_POST['$adminID[0]']
只是尝试删除撇号。