Freddy
Freddy

Reputation: 867

Executing this query if user has a row in DB, else not

I have a table called user_bio, this table has one row, which was inserted manually:

id: 1
age: 30
studying: Business
language: English
relationship_status: Single
username: conor
about_me: This is conor's bio.

I have a page called account_settings_bio.php, from where the logged in user ($username) can edit their details. At the moment, when I log in as conor, I can UPDATE my data, but say for example I log in as Alice, Alice has no row in the database, therefore, I would have to INSERT data for her, but it doesn't seem to insert a new row for her.

Here is my approach:

if ($update_bio){
            /*************************/
            // need to check if the username has data already in the db, if so, then we update the data, otherwise we insert data.
                $get_bio = mysqli_query($connect, "SELECT * FROM user_bio WHERE username ='$username'");
                $row_returned = mysqli_num_rows($get_bio);

                if ($row_returned == 1){
                    $update_details_query = mysqli_query ($connect, "UPDATE user_bio SET studying ='$new_studying', language ='$new_lang', 
                                                                relationship_status = '$new_rel', about_me = '$about_me' WHERE username ='$username'");
                } if ($row_returned == 0) {
                    $insert_query = mysqli_query ($connect, "INSERT INTO user_bio VALUES ('', '$age', '$new_lang','$new_rel', '$username', '$about_me'");
                }
                echo "  <div class='details_updated'>
                            <p> Details updated successfully! </p>
                        </div>";    
            }

The UPDATE query works fine, when logged in as conor, data does change in the db, its just the INSERT which is not working.

Upvotes: 0

Views: 38

Answers (1)

Philip
Philip

Reputation: 2988

The order of the inserted columns is not the same as in the database and there are missing some (studying). To be sure, you could rewrite your insert SQL to be more explicit:

INSERT INTO user_bio (id, age, studying, language, relationship_status, username, about_me) VALUES (NULL, '$age', '$new_studying', '$new_lang','$new_rel', '$username', '$about_me'"

Note: why not use if($row_returned==0){ /* INSERT */ } else { /* UPDATE */ } instead of a double if?

Upvotes: 0

Related Questions