如果用户在数据库中有行,则执行此查询,否则没有


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

我有一个名为user_bio的表,这个表有一行,是手动插入的:

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

我有一个名为 account_settings_bio.php 的页面,登录用户($username)可以从中编辑他们的详细信息。目前,当我以 conor 身份登录时,我可以UPDATE我的数据,但例如我以 Alice 身份登录,Alice 在数据库中没有行,因此,我必须为她INSERT数据,但它似乎没有为她插入新行。

这是我的方法:

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

UPDATE查询工作正常,当以 conor 身份登录时,数据库中的数据确实会发生变化,只是INSERT不起作用。

插入列的顺序与数据库中的顺序不同,并且缺少一些(studying)。可以肯定的是,您可以重写插入 SQL 以使其更明确:

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'"

注意:为什么不使用if($row_returned==0){ /* INSERT */ } else { /* UPDATE */ }而不是双if