简体   繁体   中英

How can I make num_rows work for this select query?

OK, so I have this strange problem. My num_rows doesn't work, I tried everything.

So the idea, is that if there are no selected rows from the database, it should show a <div> . But it doesn't.

I have no error messages, so I don't know what I can do.

<?php
    $query = $this->db->query("SELECT null FROM donations WHERE donateName = ? ORDER BY donateID DESC LIMIT 1", array(getUserData($this->session->userdata('logged_in')["id"], "name")));
    foreach($query->result() as $row) {
        if(!$query->num_rows()) { ?> 
<div class="col-lg-4">
                <div class="card">
                                            <div class="card-header">
                                                    <h5 class="card-header-text">I</h5>
                                            </div>

                                            <div class="card-block">
                        <ul style="margin-left: 25px; list-style: initial;">

                        <br><li>test</li>
                        </ul>
                                            </div>
                                    </div>
            </div>
        <?php } } ?>

Sorry, I've decided to edit my answer, since I was wrong.

You just need to remove your foreach -loop.

You should just remove the

foreach($query->result() as $row) {

(and closing } ).

as this would normally be to loop over the result set. You just want to say there are no rows so just have the if .

You could also remove the ORDER BY donateID from the SQL as it doesn't really matter what order they come back in.

If you are using codeigniter then you may like this query format.

// Model
function get_count($table, $where = array(), $fields = false) {  
    // echo"<pre>";print_r($where);exit;      
    if (!$fields) {
        $fields = '*';
    }
    $this->db->select($fields);
    $this->db->from($table);
    $this->db->where($where);

    $query = $this->db->get();
    // echo $this->db->last_query();exit;
    return $query->num_rows();
}

Call the function by providing the required arguments like

// Controller
$table = 'mytalbe';
$where = array(
  'id' => '34' // for example
);
$count = get_count($table, $where);

Hope this will help you in future to reuse the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM