我正在尝试将我从mysql获取的结果转换为php数组
谁能帮我

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "women";
    $conn = new mysqli($servername, $username, $password, $dbname);
    $id=$_GET['id'];
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql = "SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS,
                   DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`))AS DAYS
           FROM normalW
           where id = '$id'";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        foreach($new_array as $array){
            echo $row['DAYS'].'<br />';
            echo $row['MONTHS'].'<br />';
        }
    } else {
        echo "0 results";
}
$conn->close();
?>


问题解决了谢谢

最佳答案

要回答您的问题,您必须首先声明新数组
$new_array = array();

然后遍历您的查询结果以填充数组

while ($row = $result->fetch()) {
  $new_array[] = $row;
}


但是正如提到的评论之一,您确实应该使用准备好的语句来保护自己免受sql注入。

    $stmt = $mysqli->prepare("SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS, DAY(ADDDATE(ADDDATE(`dateDebutC`,  `dureeC`),`dureeR`)) AS DAYS FROM normalW where id = ?");

    /* bind parameters i means integer type */
    $stmt->bind_param("i", $id);

    $stmt->execute();

    $new_array = array();

    while($row = $stmt->fetch()) {
        $new_array[] = $row;
    }

关于php - MySQL的结果成PHP数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43297320/

10-16 11:34
查看更多