Austen Novis
Austen Novis

Reputation: 444

mysqli_query returns unexpected output

I am a beginner programmer and am having a little trouble getting information from database through mysqli_query. I first connect to the database and then attempt to get the information from the table cbo which is inside the database. I then print out what results from the query which is not the information from the table. Instead this is what I get.

mysqli_result Object
(
    [current_field] => 0
    [field_count] => 8
    [lengths] => 
    [num_rows] => 12
    [type] => 0
) 

Here is the code I am using. Dump just echos the variable.

<?php
    $con = mysqli_connect("localhost", "root", "harvard", "cbo projections");
    if ( mysqli_connect_errno() ) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $result = mysqli_query($con,"SELECT * FROM cbo");
    dump( $result );
?>

Upvotes: 1

Views: 1048

Answers (3)

martriay
martriay

Reputation: 5742

That's the mysqli object, what do you want to do with it? You should read about https://www.php.net/manual/mysqli-result.fetch-assoc.php, https://www.php.net/manual/mysqli-result.fetch-object.php or https://www.php.net/manual/mysqli-result.fetch-array.php.

By example:

<?php

$con=mysqli_connect("localhost", "root", "harvard", "cbo projections");
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM cbo");
while ($row = mysql_fetch_assoc($result)) {
    var_dump($row);
}

?>

Upvotes: 1

Odiljon Sattarov
Odiljon Sattarov

Reputation: 104

$result = mysqli_query($con,"SELECT * FROM cbo");
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
  $rows[] = $row;
}
print_r($rows);

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

$result is just an object that contains the resultset. You have to fetch data from it. Read mysqli_fetch_assoc or mysqli_fetch_array

EXAMPLE:

if ($result = mysqli_query($link, $query)) {
    while ($row = mysqli_fetch_assoc($result)) {
        //Display fields here according to your table structure
    }
    mysqli_free_result($result);
}

You could do something like

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

This will create an array named records that will contain all your fetched rows and then you can later access that array and process accordingly

Upvotes: 2

Related Questions