Jahangir Hossain
Jahangir Hossain

Reputation: 27

How to echo different string according to value of specific column of similar id?

I have a table named 'payment' and the datas are:

id   client_id   month_id
1    99          10
2    99          11
3    99          12

Now in my front-end I want to show if the client 99 has 10 value in month_id echo 'October Paid'; if there is value 11 echo 'November Paid' and similar to all the months depending on the value of month_id.

How can I achieve this? I tried this:

<?php
    $sql = "SELECT * FROM payment WHERE client_id = 99";

    $result = $connect->query($sql);
    $data = $result->fetch_array();

    $mnthId = $data['month_id'];

    if ($mnthId = 11) {
        echo "November Paid";
    } else {
        echo "Unpaid";
    }
?>

But I always get the result of first row I mean October Paid. Other if condition is not working. Any help is deeply appreciated. TIA

Upvotes: 0

Views: 89

Answers (2)

Bijay Regmi
Bijay Regmi

Reputation: 1288

You almost had it . I think this works. Havent tested it,

<?php
    $conn = mysql_connect("localhost", "mysql_user", "mysql_password");    
    $sql = "SELECT * FROM payment WHERE client_id = 99";
    $result = mysql_query($sql);

    while ($row = mysql_fetch_assoc($result)) {
        if ($row['monthid']=="10") { echo "october paid"} 
    /* all months like this */
    }

Upvotes: 0

Madhur Bhaiya
Madhur Bhaiya

Reputation: 28834

I would rather utilize Monthname() with Str_to_Date() function of the MySQL, to get month name directly from the query itself:

<?php
    $sql = "SELECT *, 
                   MONTHNAME(STR_TO_DATE(month_id, '%m')) AS month_name 
            FROM payment 
            WHERE client_id = 99";

    $result = $connect->query($sql);
    $data = $result->fetch_array();

    echo $data['month_name'] . " Paid";
?>

Refer this answer: https://stackoverflow.com/a/53213448/2469308 for additional details.

Upvotes: 1

Related Questions