简化PHP代码 - 连接数据库

时间:2016-02-18 12:40:32

标签: php mysql

这里我有一个连接数据库的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"];
}

?>

5 个答案:

答案 0 :(得分:2)

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

$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"];

答案 1 :(得分:1)

您可以为此编写一个或两个简单函数。此外,请注意您的代码容易受到SQL Injection的攻击。下面是一个如何使用一些简单函数实现此目的的示例:

<?php
    function DB() {
        $dbhost = 'localhost';
        $dbuser = 'root';
        $dbpass = '';
        $db = '_erica';
        return new mysqli($dbhost, $dbuser, $dbpass,$db);
    }

    function query($id) {
        $query = "SELECT * FROM `pics` WHERE `id` = $id";
        return DB()->query($query);
    }

    $result = query(1); // will fetch records for ID 1
    while($row = $result->fetch_assoc()) {
        $bcgrnd = $row["link"];
    }

    $result = query(2); // will fetch records for ID 2
    while($row = $result->fetch_assoc()) {
        $bcgrnd = $row["link"];
    }
?>

通过调整此方法,您可以获取特定ID的数据。如果您不喜欢此解决方案,请考虑使用MySQL IN clause

答案 2 :(得分:0)

MySQL in()函数在给定参数中找到匹配项,您可以使用它

select pics where id IN(1,2,3,4,5,6) 

答案 3 :(得分:0)

试试这个。

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

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

    $result = $conn->query($sql);

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

    ?>

答案 4 :(得分:0)

为什么不尝试查询并将其限制为6个结果,只需拉动6个结果就占用更少的资源:

SELECT * FROM `pics` ORDER BY `[PRIMARY KEY]` LIMIT 6