gpt4 book ai didi

php - PDO获取设置变量mysql php

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

我对 PHP 的 PDO 内容很陌生,所以我想知道如何将数据分配给变量。

我收到这个Array ( [0] => Array ( [id] => 1 [title] => Test Announcement! [link] => http://www.google.com ) )当它返回时。

我希望它只是“测试公告”和“http://www.google.com”,并且能够将它们签名到 $title 和 $link 等变量。

函数.php

<?php
require("common.php");
function getAnnouncements() {
$query = "SELECT title, link FROM announcements";

try {
global $db;
// Execute the query against the database
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
print_r($result);

}
catch(PDOException $ex) {
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Error loading announcements");
}

}

?>

我使用了 kypros 答案,现在我有这个:

<?php
require("common.php");
function getAnnouncements() {
$query = "SELECT title, link FROM announcements";

try {
global $db;
// Execute the query against the database
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $announcement)
$title = $announcement['title'];
$link = $announcement['link'];
echo "<a href='".$link."'>".$title."</a>";
}
}
catch(PDOException $ex) {
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Error loading announcements");
}

}

?>

带有错误日志和空白白页。

[18-Oct-2014 13:28:12 UTC] PHP Parse error:  syntax error, unexpected '}', expecting T_CATCH in /home/dxbridge/public_html/scripts/functions.php on line 17
[18-Oct-2014 13:28:13 UTC] PHP Parse error: syntax error, unexpected '}', expecting T_CATCH in /home/dxbridge/public_html/scripts/functions.php on line 17

最佳答案

您的 $result 现在包含与您的 select 语句匹配的所有行。要访问各个列的值,您可以执行以下操作:

foreach($result as $announcement)
{
$title = $announcement['title'];
$link = $announcement['link'];
echo "<a href='".$link."'>".$title."</a>";
}

这将输出一个超链接,将每个公告链接到一个链接并仅显示其标题

关于php - PDO获取设置变量mysql php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26440130/

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