duanqian2278 2016-03-20 14:44
浏览 120
已采纳

如何将mySQL转换为PDO

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;
}}
  • 写回答

2条回答 默认 最新

  • doudouchan5830 2016-03-20 15:02
    关注

    In your original MySQL_ query you have:

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

    So, if your old query work, new execute must be this:

    $stmt->execute(array(
        ':adminID' => $adminID[0],
        ':genAnnouncement' => $genAnnouncement));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?