gpt4 book ai didi

PHP PDO MYSQL 连接

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

我有一个名为 cms_page 的表,其中每个页面都有一个 ID。我想从该表中提取所有信息,并从 cms_page_part 表中提取所有信息,其中 page_id 等于我发送到页面的 ID...我知道这很令人困惑,但这是我的尝试:

require '../../config.php';
$conn = new PDO(DB_DSN, DB_USER, DB_PASS);

$id = (int)$_GET['id'];
//$q = $conn->query("SELECT * FROM cms_page WHERE id=$id");
$q = $conn->query("SELECT cms_page.id, cms_page.title, cms_page.slug, cms_page_part.* FROM cms_page LEFT JOIN cms_page_part ON cms_page_part.page_id=cms_page.id WHERE cms_page.id = $id");

$project = $q->fetch(PDO::FETCH_ASSOC);

任何关于如何加入这些的帮助将不胜感激。

最佳答案

如何连接两个表:

SELECT id, title, slug, cms_page_part.* FROM cms_page JOIN cms_page_part ON cms_page.id = cms_page_part.page_id WHERE cms_page.id=$id

我在评论中所说的示例:

// Connect to database
$conn = new PDO(DB_DSN, DB_USER, DB_PASS);

// Page ID
$id = (int) $_GET['id'];

// Fetch page
$pageStmt = $conn->query(sprintf('SELECT * FROM cms_page WHERE id=%d', $id));
if ($pageStmt->fetchColumn() != 0) {
$page = $pageStmt->fetch(PDO::FETCH_ASSOC);

// Fetch parts
$partsStmt = $conn->query(sprintf('SELECT * FROM cms_page_parts WHERE page_id=%d', $id));
while ($part = $partsStmt->fetch(PDO::FETCH_ASSOC)) {
// ...
}
$partsStmt->closeCursor();
}
$pageStmt->closeCursor();

示例(带有准备好的语句):

// Connect to database
$conn = new PDO(DB_DSN, DB_USER, DB_PASS);

// Page ID
$id = (int) $_GET['id'];

// Fetch page
$pageStmt = $conn->query('SELECT * FROM cms_page WHERE id=:id');
if ($pageStmt->execute(array(':id' => $id))) {
if ($pageStmt->fetchColumn() != 0) {
$page = $pageStmt->fetch(PDO::FETCH_ASSOC);

// Fetch parts
$partsStmt = $conn->query('SELECT * FROM cms_page_parts WHERE page_id=:id');
if ($partsStmt->execute(array(':id' => $id))) {
while ($part = $partsStmt->fetch(PDO::FETCH_ASSOC)) {
// ...
}
$partsStmt->closeCursor();
}
}
$pageStmt->closeCursor();
}

关于PHP PDO MYSQL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1805698/

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