gpt4 book ai didi

php - 如何将 mySQL 转换为 PDO

转载 作者:行者123 更新时间:2023-12-01 00:39:42 24 4
gpt4 key购买 nike

我有这个 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;
}}

最佳答案

在你原来的 MySQL_ 查询中你有:

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

因此,如果您的旧查询有效,新的execute 必须是这样的:

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

关于php - 如何将 mySQL 转换为 PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36115139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com