gpt4 book ai didi

php - 尝试执行 INSERT 命令时 PDO 不起作用

转载 作者:行者123 更新时间:2023-11-29 10:02:08 24 4
gpt4 key购买 nike

我正在尝试插入 SQL 查询,但它不起作用 - 我没有错误,$pdo->errorInfo(); 仅返回 Array 并在mysql没什么可看的!我 100% 确定 $text、$file 和 $title 已设置(我已使用 echo 检查)在每个其他 php 文件中,此 pdo 连接都可与 include 配合使用,但是不在 dev.php 中我该怎么办???

datenbank.php

<?php
$pdo = new PDO('mysql:host=localhost;dbname=db', 'user', 'password');
?>

dev.php

include("datenbank.php");
// Prepare an insert statement
$post = $pdo->prepare("INSERT INTO news (text, date, file, title) VALUES ($text, NOW(), $file, $title)");
$post->execute();
$help = $pdo->errorInfo();

最佳答案

您没有在 prepare PDO 语句中使用参数标记。当您使用 PDO 扩展准备查询时,您需要在查询语句中放置标记,并像关联数组一样在 execute 函数中指示这些标记的值。

您可以使用 :marker 或问号 ? 等标记,您的查询将如下所示:

include("datenbank.php");
// Prepare an insert statement with marks params
$post = $pdo->prepare(INSERT INTO news (text, date, file, title) VALUES (:text, NOW(), :file, :title));
//execute statements with the marks values in prapare function params
$post->execute(array(':text' => $text, ':file' => $file, ':title' => $title));

编辑:PD:这可以防止 SQL 注入(inject)......

关于php - 尝试执行 INSERT 命令时 PDO 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52698138/

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