Mithu
Mithu

Reputation: 655

WordPress insert statement based on a database value

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";
    }
?>

Upvotes: 0

Views: 61

Answers (1)

Alberto Martinez
Alberto Martinez

Reputation: 2670

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)

Upvotes: 1

Related Questions