Mithu Mithu - 3 years ago 148
MySQL Question

WordPress check empty data in a query

I am displaying some data from wp_share table using a

foreach loop
. What I am trying if there is no-data then it will show a msg like "there is no data found" and if found then it will go to the loop.

Following code I have written but it is always getting the empty value, though there is data actually.

<?php

$me=$current_user->user_login;
$retrieve_data = $wpdb->get_results( "SELECT * FROM wp_share where Status='onsell' and user!='$me'" );
echo '<table border=0 class="table">
<tr> <th colspan="5" style="color:blue;border-bottom:2px solid blue;"> Purchase share from user offer</th> </tr>

<tr><th>OfferBy</th><th>OfferValue</th><th>Qnty</th> <th> ref</th> <th> action</th></tr>';


if (mysql_num_rows($retrieve_data)<=0) {
echo '<tr><td style="color:crimson;">' ."there is no data found". '</td>';
}

else{
foreach ($retrieve_data as $retrieved_data){

echo '<tr><td>'. $retrieved_data->user.'</td>';
echo '<td>'.$retrieved_data->offervalue.'</td>';

echo '<td>'. $retrieved_data->user.'</td>';
echo '<td>'. $retrieved_data->id.'</td>';
}
?>

Answer Source

In your code there are many error available . mysql_num_rows is not used in WordPress. In WordPress to check number of row in result used $wpdb->num_rows

Try below code it help you

<?php 
global $wpdb;
$me=$current_user->user_login;
$retrieve_data = $wpdb->get_results( "SELECT * FROM wp_share where Status='onsell' and user!='".$me."'" );
echo '<table border=0 class="table">
<tr> <th colspan="5" style="color:blue;border-bottom:2px solid blue;"> Purchase share from user offer</th> </tr><tr><th>OfferBy</th><th>OfferValue</th><th>Qnty</th> <th> ref</th> <th> action</th></tr>';


if ($wpdb->num_rows<=0) {
    echo '<tr><td style="color:crimson;">'  ."there is no data found". '</td>';
}else{
    foreach ($retrieve_data as $retrieved_data){

        echo '<tr><td>'. $retrieved_data->user.'</td>';
        echo '<td>'.$retrieved_data->offervalue.'</td>';

        echo '<td>'. $retrieved_data->user.'</td>';
        echo '<td>'. $retrieved_data->id.'</td></tr>';
    }
}
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download