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条)

报告相同问题?