dongtan7418 2015-04-05 21:20
浏览 62
已采纳

如何在MySQL表中为同一行的两列插入值

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.

  • 写回答

2条回答 默认 最新

  • duanlian1960 2015-04-05 21:29
    关注

    Insert can off 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c