sps
sps

Reputation: 2720

How to insert value for two columns of same row in MySQL table

My database (MySQL) has a table members1, with columns username and password.

I am taking the username and password from html web page and using php to update the database.

Below is the php code:

$flag = 0;
$sql = "SELECT username FROM members1";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) 
    {
        while($row = $result->fetch_assoc()) 
        {
            if ($row["username"] == $_POST["username"])
            {                   
                {
                    $flag = 1;
                    echo "<h3>This username already exists.</h3>";
                    echo "Please try with a different username.<br/>";
                    echo "<br/><a href=sign_up.html>Try again</a>";
                    break;
                }                
            }
        }
        /* If username is unique */
        if ($flag == 0)
        {
            /* PROBLEM LIES HERE */
            $sql = "INSERT INTO  `dbname`.`members1` (`username`) VALUES ('" . $_POST["username"] . "')" ; 
            $sql2 = "INSERT INTO  `dbname`. `members1` (`password`) VALUES ('" . $_POST["pass1"] . "')";
            $conn->query($sql);
            $conn->query($sql2);
            echo "<h3>Signup successfull.</h3>You can now login with your username and password.";              
        }
    } 
$conn->close();

But after a give username and password in front end, and when I check the database, I see that username is inserted in one row, and password is inserted to next row.

I am working in my own front-end project, but i thought i will atleast add a signup-login functionality. So I just followed some short tutorials available online to do this. I guess I have made a mistake.

Anyone could suggest how to fix this ? I know I have to change $sql and $sq2 but not sure what to do.

thanks.

Upvotes: 0

Views: 1904

Answers (2)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39109

Insert can, of course, fill multiple fields at a time :

$sql = "INSERT INTO  `dbname`.`members1` (`username`,`password`) VALUES ('" . $_POST["username"] . "','" . $_POST["pass1"] . "')" ; 
$conn->query($sql);

I would also suggest you to inform about where close

$sql = "SELECT username FROM members1 WHERE username = '".$_POST["username"]."'";

Or even try better and add unique index on your username field

And maybe even be adventurous and learn about security and prepared statement.

Upvotes: 1

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11055

You have to insert values at once:

 $sql = "INSERT INTO  `dbname`.`members1` (`username`,`password`) VALUES ('" . $_POST["username"] . "'," . $_POST["pass1"] . "')" ; 

Upvotes: 1

Related Questions