Search code examples
phpwebserver

Angular $http.get doesn't return what i expected


I'm trying to do a simple http get request but it doesn't return what i expected.

Here is the code

.js :

$http.get("database.php").success(function(data, status)
{
    alert(data);
    $scope.data = data;
}
).error(function(data, status)
{
    $scope.untruc = "Error";
});

.php :

<?php
header('Content-type: application/json');

$conn = // my connection

// Check connection
if ($conn->connect_error)
    echo "Connection failed";
else
{
    $sql = "SELECT id FROM user";
    $result = $conn->query($sql);
    echo json_encode($result);
}

?>

and the ouput is :

data : <?php header('Content-type: application/json'); $conn = // my connection; // Check connection    if ($conn->connect_error) echo "Connection failed"; else { $sql = "SELECT id FROM user"; $result = $conn->query($sql); echo json_encode($result); } ?>

literaly the code...

I'm expecting it to get the $result. Do you know how i could do that ?


Solution

  • Please check you php code once. And try to implement this code

    <?php
    header('Content-type: application/json');
    
    $conn = new mysqli('localhost', 'root', 'password', 'database');
    
    // Check connection
    if ($conn->connect_error)
        echo "Connection failed";
    else
    {
        $sql = "SELECT * FROM users";
        $result = $conn->query($sql);
        $myresult = [];
        $i =0;
        while($row = $result->fetch_array()) {
    		$myresult[$i] = $row;
    		$i++;
    	}
        
        //echo "<pre>";
        echo json_encode($myresult);
    }
    
    ?>