0

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

  • 1
    You never set `$new_array`... fetch the `$result`. You also should parameterize that query, your open to injections as is. – chris85 Apr 08 '17 at 16:10
  • Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Apr 08 '17 at 16:28
  • Can you give an example of your required result please. Right now it is not very clear what you want to do – RiggsFolly Apr 08 '17 at 16:29
  • You are supposed to mark an answer as **accepted answer**, so that other viewer of this question can read the accurate answer of this question easily. – Siraj Alam Apr 20 '17 at 13:10

1 Answers1

0

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;
    }
Ryan Tuosto
  • 1,941
  • 15
  • 23