Why this code does not fetch query as I expect?

63 Views Asked by At

If I run this following sql

SELECT date, SUM(nmbr_of_guests) FROM guest_tbl WHERE date = "2015-06-30"

I am getting this :

after running query

This what I am trying to get NUMBER(SUM) OF TOTAL VALUE of the row nmbr_of_guests for a specific date. What I have to do is now I wanna get the same results (shown in screen shot) when the date is dynamically input via a form.

After I created the form I put this as form action

if (isset($_POST['search'])){
$serch_text = $_POST["search_text"]; 
$con=mysqli_connect("localhost","root","","guest");
    // Check connection
    if (mysqli_connect_errno()) {
      die ("Failed to connect to MySQL: " . mysqli_connect_error());
    }       
    $searching_date = $serch_text;
    $searchroute = "select * from guest_tbl where date = '$searching_date'";
    $result = $con->query($searchroute);
    $row = $result->fetch_assoc();
    if ($row == 0) { echo '<div style="color: red;">We could not find the Reference ID: <b>' . $serch_text . '</b>. Please refine your reference ID</div>' ; 
    } else {        
        echo '<h3>Total guest for the day : '. $serch_text .'</h3>';        
        $total_guests = mysqli_query($con, 'SELECT date, SUM(nmbr_of_guests) FROM guest_tbl WHERE date = "'.$serch_text.'"');               
        echo $total_guests;
        mysqli_close($con);
    }
}

Now if I select search for 2015-06-30 via form I am getting Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\guest\index.php on line 26

Line 26 is echo $total_guests;

If I change echo $total_guests;

To

echo $total_guests->fetch_assoc();

I am getting Notice: Array to string conversion in C:\xampp\htdocs\guest\index.php on line 25 Array

Now the line 25 is echo $total_guests->fetch_assoc();

How can I get the total value (Sum of nmbr_of_guests) for a specific date?

1

There are 1 best solutions below

0
On BEST ANSWER

As the error says, fetch_assoc returns an array, so do print_r($total_quests->getch_assoc()) and see the structure of the array. You propably will have to pick up the first one result, but I suggest you to do it using foreach loop.