javascriptphpmysqlhosted

PHP code not returning correct MySQL result


I'm querying a set of data from MySQL on a hosted server. When I did it on my local machine, it worked fine, but on the hosted server, it's not returning anything. The weird thing is, when I use this GUI for the hosted environment to run the same query, it does return the results.

So here are some codes, etc.

This is index.php:

<?php

$servername = "username.db.theservername.ether.com";
$mysqllogin = "username";
$mysqlpassword = "thepassword";
$dbName = "StepsMath";
$conn = new mysqli($servername, $mysqllogin, $mysqlpassword, $dbName);

if($conn->connect_error){
    die ("connection failed: " . $conn->connect_error);
    echo "connection failed.";
}

$set_name = 'test_set';
$query = "select word, definition from word_list where set_name = '$set_name'";
$result = $conn->query($query);
$conn->close();
             // *********************************************
echo $query; // <-------- *******this prints the query*******
             // *********************************************
$result = mysqli_fetch_array($result);

?>

<!DOCTYPE html>
<html lang="en"><head>
<title>this is a title</title>

<script type="text/javascript">
    var json = '<?= json_encode($result) ?>';
    var word_list = JSON.parse(json);
    console.log(word_list);     //line 24
    console.log(json);          //line 25
    function getUserId(){
        return '<?= $user_id ?>';
    }
    if(!getUserId()) window.location = 'login.html';
</script>
</head>
<body>body stuff</body>
</html>

Table word_list only has three columns: word, definition, and set_name

The above code is supposed to return rows of words and definitions. Instead, as I check in the browser console, it returns the following:

{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}

This is the query that runs:

select word, definition from word_list where set_name = 'test_set'

If I copy that exact query and run it in the MySQL GUI in the hosted server,

GUI MySQL environment provided by GoDaddy

the following is returned:

Result of running the same query in GUI

So to summarize the question, why is there a discrepancy in the result between the GUI and the code??


Solution

  • change this line:

    $result = mysqli_fetch_array($result);
    

    to this:

    while ($row = mysqli_fetch_assoc($result)) {
        $res[] = $row;
    }
    var_dump($res);
    

    The information you previously got: {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} are all mysqli_result properties.

    Read this, it will help you uderstand what you did wrong:http://php.net/manual/en/class.mysqli-result.php