mysql结果进入php数组

时间:2017-04-08 16:09:01

标签: php mysql

我正在尝试将我从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();
?>

问题解决了谢谢你们

1 个答案:

答案 0 :(得分:0)

要回答您的问题,您必须先声明新数组 $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;
    }