dongye8110 2015-08-15 13:40
浏览 17
已采纳

无法使用php和sql将数据插入数据库[关闭]

I have tried the following code but it does not work.

Code

<?php
if (!empty($_POST)) {
     $mysqli = new mysqli('localhost', 'root', '123', 'users');

     if ($mysqli->connect_error) {
        die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
     }

     $sql = "INSERT INTO users ( username, email ) VALUES ( '{$mysqli->real_escape_string($_POST['username'])}', '{$mysqli->real_escape_string($_POST['email'])}' )";
     $insert = $mysqli->query($sql);

     if ($insert) {
        echo "Success! Row ID: {$mysqli->insert_id}";
     } else {
        die("Error: {$mysqli->errno} : {$mysqli->error}");
     }

     $mysqli->close();
}
?>
<form action="main.php" method="post">
    <input type="text" id="SIMOMO"  name="username" minlegth="5" maxlength="30" class="pad" required> 
    <input type="text" ID="FLOBIT"name="email" class="pad" required >
    <input type="submit">
</form>
  • 写回答

2条回答 默认 最新

  • duangua5308 2015-08-15 14:29
    关注

    Try this:

    <?php  
    if ($_POST['sub']) {
    $server = "localhost";
    $username = "yourusernamehere";
    $pass = "yourpasswordhere";
    $db = "users";
    // Create connection
    $mysqli = new mysqli($server, $username, $pass, $db);
    // Check connection
    if ($mysqli->connect_error) {
        die("Connection failed: " . $mysqli->connect_error);
    }
    echo "Connected successfully";
    
    
    $uname = mysql_escape_string($_POST['username'])
    $mail = mysql_escape_string($_POST['email']);        
    $sql = "INSERT INTO users (username, email) VALUES ('$uname', '$mail')";
    $insert = $mysqli->query($sql);
    if ($insert){
      echo "Success! Row ID: {$mysqli->insert_id}";
      header("Location:main.php");
      } else {
       die("Error: {$mysqli->errno} : {$mysqli->error}");
      }
      $mysqli->close();
            }
    ?>
    
    
    <!DOCTYPE html>
    <html>
    <body>
            <form action = "" method = "POST">
            <label>Enter your Username:</label>
            <input type="text"  name="username" required>
            <label>Enter your Email:</label>        
            <input type="email"  name="email" required >
             <input type="hidden" name = "check">
             <input type="submit" name = "sub" value = "INSERT">
            </form>
    </body>
    </html>
    

    Your database name as it lookes on the third line is 'users' and so is the name of your table that you are trying to INSERT INTO into "users' line 10. Are you sure your are not messing up there?

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化