gpt4 book ai didi

php - 简化php代码——连接数据库

转载 作者:太空宇宙 更新时间:2023-11-03 11:51:10 25 4
gpt4 key购买 nike

这里我有一个连接到数据库的 php 代码,通过 id 选择一行并使用 while 循环从该行创建一个关联数组。我是否必须一遍又一遍地编写此代码才能通过 id 从其他行创建数组?也许有机会以某种方式简化此 php 代码?请看我的代码。顺便说一句,我是 php 的新手...

<?php    
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);

$sql1 = "SELECT * FROM pics WHERE id = 1;";
$sql2 = "SELECT * FROM pics WHERE id = 2;";
$sql3 = "SELECT * FROM pics WHERE id = 3;";
$sql4 = "SELECT * FROM pics WHERE id = 4;";
$sql5 = "SELECT * FROM pics WHERE id = 5;";
$sql6 = "SELECT * FROM pics WHERE id = 6;";
$result1 = $conn->query($sql1);
$result2 = $conn->query($sql2);
$result3 = $conn->query($sql3);
$result4 = $conn->query($sql4);
$result5 = $conn->query($sql5);
$result6 = $conn->query($sql6);

while($row1 = $result1->fetch_assoc()) {
$bcgrnd = $row1["link"];
}

while($row2 = $result2->fetch_assoc()) {
$recipes = $row2["link"];
}

while($row3 = $result3->fetch_assoc()) {
$header = $row3["link"];
}

while($row4 = $result4->fetch_assoc()) {
$menu = $row4["link"];
}
while($row5 = $result5->fetch_assoc()) {
$beauty = $row5["link"];
}

while($row6 = $result6->fetch_assoc()) {
$kids = $row6["link"];
}

?>

最佳答案

您可以在一个查询中执行此操作:

$sql = "SELECT * FROM pics WHERE id IN (1,2,3,4,5,6);";
$result = $conn->query($sql);

然后你可以像这样遍历所有结果:

$data = array();
while ($row = $result->fetch_assoc()) {
$id = $row["id"];
$link = $row["link"];
$data[$id]["link"] = $link;

// add more fields if you want
}

要访问例如 ID 1 的链接,只需执行以下操作:

$data[1]["link"];

关于php - 简化php代码——连接数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35481761/

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