Reputation: 85
I am trying to interrogate a database, but mysqli_query($dbc, $query) always returns {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
I do not have any var_dump in the code.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()){
trigger_error ('Could not connect to MySql: ' . mysqli_connect_error());
echo "it had an error";
} else {
mysqli_set_charset($dbc, 'utf8');
echo "it connected";
}
this echoes "it connected"
function getGames($dbc){
$query="SELECT * FROM games WHERE min_players <= ".$number." AND max_players >=".$number.";";
$result = mysqli_query($dbc, $query) or trigger_error("Query: $query\ n<br />MySQL Error: " . mysqli_error($dbc));
if(mysqli_affected_rows($dbc)) {
return $result;
} else {
return "no affected rows";
}
}
When I run my query in phpMyAdmin, I get several lines of results.
Also, the function doesn't return "no affected rows" when it is called:
$result = getGames($dbc);
echo json_encode($result);
Upvotes: 1
Views: 5078
Reputation: 1062
I just changed your mysqli_affected_rows($dbc) to mysqli_num_rows($result), and works for me. mysqli_affected_rows($dbc) Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.
function getGames($dbc){
$query="SELECT * FROM games WHERE min_players <= ".$number." AND max_players >=".$number.";";
$result = mysqli_query($dbc, $query) or trigger_error("Query: $query\ n
MySQL Error: " . mysqli_error($dbc));
if(mysqli_num_rows($result)) {
return $result;
} else {
return "no affected rows";
}
}
Upvotes: 1
Reputation: 6269
Unless you're declaring $number
globally, it won't be available in the scope of getGames
. You should pass it in:
function getGames($dbc, $number) {
// ...
Additionally, you could output the exact SQL
that you're running so you can test it in phpMyAdmin (and so you can verify that $number
is correctly being passed to your function):
echo $query;
Finally, mysqli_affected_rows
doesn't return the number of rows in SELECT
statements. Try mysqli_num_rows
instead:
$sql = sprintf('Your SELECT statement with %d number', $number);
echo $sql; // To visually verify the SQL is valid
$query = mysqli_query($dbc, $sql);
if (false !== $query) {
return mysqli_num_rows($query);
} else {
return mysqli_error($dbc);
}
Upvotes: 2