简体   繁体   中英

mysql result into php array

I'm trying to convert the result that i'm getting from mysql to a php array can anyone helps me

<?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();
?>

Problem solved Thank you guys

To answer your question you must first declare the new array $new_array = array();

Then loop through your query results to populated the array

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

But as one of the comments mentioned you really should be using prepared statements to protect yourself from sql injection.

    $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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM