0

I have a table where I store information about users monthly activities. The table is as follows:

+-------------------------------------------+
|user_id   | month | year | value1 | value2 |
+-------------------------------------------+
|1         | 10    | 15   | 45     | 78     |
+-------------------------------------------+

Let's say I have 3 users with ids 1, 2 and 3.

What I'd like to do is : when I submit the request to display records from the table for a given month and year, display the result above + create records with values set at "0" for that given month and year if user doesn't have record. It'd display this :

+-------------------------------------------+
|user_id   | month | year | value1 | value2 |
+-------------------------------------------+
|1         | 10    | 15   | 45     | 78     |
|2         | 10    | 15   | 0      | 0      |
|3         | 10    | 15   | 0      | 0      |
+-------------------------------------------+

I managed to do it hardcoding it per user-id but I haven't been able to automate it to do: for each user that doesn't exist in ACTIVITIES where month=$month and year=$year insert (user_id,month,year,0,0).

This is what I got:

$result = mysqli_query($conn,"
    SELECT
        * FROM ACTIVITIES
    WHERE
        person_id = '2'
        AND month = '$month'
        AND year = '$year'
    ");

    if(mysqli_affected_rows($conn) > 0)
        {

        }
    else
        {
            mysqli_query($conn,"
            INSERT INTO ACTIVITIES
                (person_id, month, year, value1, value2)
            VALUES
                ('2', $mois, $annee, '0', '0')");
        }

Thx for the help. sb

1 Answer 1

2

Try using mysqli_num_rows()

if(mysqli_num_rows($result) > 0){

} else {
    //insert here
}
Sign up to request clarification or add additional context in comments.

4 Comments

thx. my request works as is. What I need is to automate the creation of "0 records". Sth like : if user-id doesn't exist in table ACTIVITIES where month=$month and year=$year, INSERT record.
okay. sorry. So I have the ACTIVITIES table as described in my post. I'd like to insert in that table a record like this ($user-id, $month,$year,'0','0') for every user that doesn't have a record in ACTIVITIES for the specified month and year. For example, user 2 and 3 don't have records for 10.2015 (see my original post). The page should then INSERT (2,10,2015,0,0) and (3,10,2015,0,0) into activities and do so for every user that doesn't exist in ACTIVITIES. Better?
i understood... what problem now?? not able to insert the data??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.