gpt4 book ai didi

php - 将mysql转换成PDO格式

转载 作者:行者123 更新时间:2023-11-29 04:44:44 25 4
gpt4 key购买 nike

我正在尝试将一些旧的 php mysql 代码转换为 PDO 格式,但卡住了。我看过这里的其他帖子,但不太明白。

这是旧代码:

<?php

if (isset($_POST['query'])) {
// Connect to database
mysql_connect("localhost", "xxxxx", "xxxxx");
mysql_select_db("xxxxx");

// Retrieve the query
$query = $_POST['query'];

// Search the database for all similar items
$sql = mysql_query("SELECT * FROM articles WHERE title LIKE '%{$query}%'");
$array = array();

while ($row = mysql_fetch_assoc($sql))
{
$array[] = $row['title'];
}

// Return the json array
echo json_encode($array);

}

?>

这就是我设法做到的,但我认为“while”部分有问题。

<?php

if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

// Retrieve the query
$query = $_POST['query'];

// Search the database for all similar items
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();

while ($row = $sql->fetchAll()) {
$array[] = $row['title'];
}

// Return the json array
echo json_encode($array);

}

?>

最佳答案

您正在尝试对字符串“sql”调用fetchAll

现在,您可以使用query,但我建议您改用prepare(出于安全原因,因为您插入了POST 数据)。

$q = $conn->prepare("SELECT * FROM articles WHERE title LIKE CONCAT('%', ? ,'%')");
$q->execute(array($query));

// result contains all returned data
$result = $q->fetchAll();

// or row by row
while($row = $q->fetch())

关于php - 将mysql转换成PDO格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21046268/

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