PHP mysql select returning null values inside response object

时间:2018-03-25 20:22:46

标签: php mysql

I can't find anything similar when searching. I'm doing the following in XAMPP for Windows 10:

When the query below is run in PHP, the result object contains null values in its fields. The result itself is not null, it's all the fields inside:

$getSessionsQuery = "select * from transaction";
$result = mysqli_query($conn, $getSessionsQuery);
// returns: 
//{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
// same results if I run $result = $conn->query($getSessionsQuery);

However, when executing the same query in phpMyAdmin, I get all the rows I had inserted. This is odd, because the table rows were populated by PHP code.

Screenshot of query results.

Can anyone tell me what I might be doing wrong in the PHP?

3 个答案:

答案 0 :(得分:1)

The problem is obviously with you connection resource $conn. I have a guess, that this resource is not visible in the context, where you run your query. If you run it inside some class method or a function, then make this $conn resource visible to this method/function, for example by passing it as one of its arguments:

// in pseudo-code
public function method($conn, ...) {
    $getSessionsQuery = "select * from transaction";
    $result = mysqli_query($conn, $getSessionsQuery);
    ...
}

答案 1 :(得分:1)

Please encode your table name, transaction is a keyword in sql.

$sql = "SELECT * FROM `transaction`";

答案 2 :(得分:0)

You need to fetch your query as array.

$query = $conn->query($getSessionsQuery);

Then, take all query results.

/** @var $res array = [int, array] */
$res = [];  

while ($r = $query->fetch_array(MYSQLI_ASSOC)) {
  $res[] = $r;
}

$query->free(); // free result

return $res;

To make it looks simple, we can create it as function:

function getTransactions($conn, $query) : array {
 /** @var $res array = [int, array] */
 $res = [];

 $mQuery = $conn->query($query);
 while ($r = $mQuery->fetch_array(MYSQLI_ASSOC)) {
  $res[] = $r;
 }

 $mQuery->free();

 return $res;
}

Make sure your query are valid! If you need more references, open PHP Manual.