Pregunta

<?php

include_once 'DB_Connect.php';

function getCategories() {
    $db = new DB_Connect();
    // array for json response
    $response = array();
    $response["Student"] = array();

    // Mysql select query
    $result = mysql_query("SELECT * FROM Student");

    while ($row = mysql_fetch_array($result)) {
        // temporary array to create single category
        $tmp = array();
        $tmp["id"] = $row["id"];
        $tmp["name"] = $row["name"];
        $tmp["number"] = $row["number"];
        $tmp["address"] = $row["address"];
        // push category to final json array
        array_push($response["Student"], $tmp);
    }

    // keeping response header to json
    header('Content-Type: application/json');

    // echoing json result
    echo json_encode($response);
}

getCategories();

?>

I have this API for my Android app, but I have a problem with this error below. Any idea out there?

<br />
<b>Warning</b>: mysql_fetch_array() expects parameter 1 to be resource, boolean given in <b>...\get_Student.php</b> on line <b>13</b><br />
{"Student":[]}
¿Fue útil?

Solución

mysql_* is officially deprecated. Use either PDO or mysqli. This is how you do it with MySQLi library:

<?php

// Connect To Db
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

// Query Function
function getCategories()
{
    // Init
    global $mysqli;
    $response = array('Student' => array());

    // Query Db
    $query = "SELECT * FROM Student";
    if ($result = $mysqli->query($query)) {
        while ($row = $result->fetch_assoc()) {
            $response['Student'][] = array(
                'id'      => $row['id'],
                'name'    => $row['name'],
                'number'  => $row['number'],
                'address' => $row['address'],
            );
        }
        $result->free(); // free up memory
    }

    // Finished
    header('Content-Type: application/json');
    exit(json_encode(response));
}

// Test
getCategories();

// Close Db Connect
$mysqli->close();

You can have this code:

// Connect To Db
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

In a file called db_connect.php and you can include it on the script you require db connection. Because the variable $mysqli is initiated outside of the function() { ... } scope; you need to use global $mysqli; to get access to it. This applies regardless of the connection code being on same file or being included from external file. Happy coding.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top