0

I am trying to insert statement in [share] table and update statement in [balance] table if balance is greater than or equal to 75 in balance table, But it is going to the else statement always, even though it meets necessary condition balance>=75

Following is my code:

<?php
if (isset($_POST['submit'])) {
    $site = htmlspecialchars($_POST['site']);
    $me=$current_user->user_login;
    $today = date('Y-m-d');
    $me=$current_user->user_login;
    $table_balance = $wpdb->prefix . "balance";
    $result = $wpdb->get_results(
        "SELECT Balance FROM $table_balance WHERE User= '$me'"
    );

    if ($result && mysql_num_rows($result)>=75) {
        $random = uniqid();
        $table_share = $wpdb->prefix . "share";
        $wpdb->insert( $table_share, array(
            'id' => $random,  
            'purchasedate' => $today, 
            'purchasevalue' => 75,
            'offervalue' => 0, 
            'status' => Active,
            'user' => $me, 
            'monthlyearnings' => 2,
        ));

        $sum=75;
        $table_balance = $wpdb->prefix . "balance";
        $wpdb->update(
            "$table_balance SET Balance=Balance-$sum WHERE User = '$me'"
        );
        echo "Purchased made successfully";
        exit();
    } else {
        echo "sorry!you dont have required amount.pls add required amount";
    }
?>

1 Answer 1

1

You are using the wrong function for checking the value of the database, mysql_num_rows() returns the number of rows returned by the query, in this case probably 1, and being smaller than 75 the else get always executed.

To obtain the balance you need to use fetch_row, something like this:

if ($result && ($row = $result->fetch_row()) && $row[0]>=75)

Edit: I put what you would use using the standard mysqli_stmt::get_result but you are using wpdb::get_results, so the instead you have to use:

if ($result && $result[0]->Balance>=75)
Sign up to request clarification or add additional context in comments.

2 Comments

hi thnks but now it is giving Fatal error: Call to a member function fetch_row() on array, however i have modified the query like following '$result = $wpdb->get_var("SELECT Balance FROM $table_balance WHERE User= '$me'"); if($result && $result>=75)' and its working.Thanks for your help
My bad, I put how you would get the results using the standard mysqli_stmt::get_result() but your are using wpdb::get_results(), which is different. Anyway wpdb::get_var() is better in this case since you only want to get only one vale of a single row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.