dongren2128 2016-02-18 12:40
浏览 42

简化PHP代码 - 连接数据库

Here I have a php code that connects to a database, selects a row by id and creates an associative array from this row using a while loop. Do I have to write this code over and over again to create arrays from other rows by id? Maybe there is a chance to simplify this php code somehow? Please look at my code. BTW I am new in 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"];
}

?>
  • 写回答

5条回答 默认 最新

  • dsbckxk165039 2016-02-18 12:45
    关注

    You can do this in one query:

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

    And then you can loop over all results like this:

    $data = array();
    while ($row = $result->fetch_assoc()) {
        $id = $row["id"];
        $link = $row["link"];
        $data[$id]["link"] = $link;
    
        // add more fields if you want
    }
    

    To access for example the link of ID 1, just do:

    $data[1]["link"];
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试