如何使用自己的脚本使用php和sql从表单中插入值?

时间:2019-02-27 21:07:10

标签: php html sql mysqli

初次使用PHP的用户和初学者,

如何使用php和sql从表单中插入值。

我已经使用php和sql创建了以下代码。 这是我的表格。

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
?>
<form action="/t.php" method="post">
  First name:
  <input type="text" name="firstname">
   <br> Last Name:
   <input type="text" name="lastname">
    <br>Email:
   <input type="text" name="email">
  <input type="submit" value="Submit">
</form>

<?php
// set parameters and execute
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$stmt->execute();


$stmt->close();
$conn->close();
?>

t.php文件只是说条目已成功添加,即使那里没有逻辑,只是一个简单的回声注释。

我只想知道如何使用带有php和sql的表单插入数据。

3 个答案:

答案 0 :(得分:1)

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>   

<form action="/t.php" method="post">
      First name:
      <input type="text" name="firstname">
       <br> Last Name:
       <input type="text" name="lastname">
        <br>Email:
       <input type="text" name="email">
      <input type="submit" name="submit" value="Submit">
    </form>



    <?php
    if(isset($_POST['submit']) && !empty($_POST['submit'])) {
    // set parameters and execute
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $email = $_POST['email'];

    // prepare and bind with form attached.
    $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $firstname, $lastname, $email);
    $stmt->execute();
    $stmt->close();
    $conn->close();
    }
    ?>

答案 1 :(得分:0)

您可以这样做:

为防止重复,请将数据库连接保存在名为db.php的文件中。

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

然后,将其包含在main.php文件中。这是用prepared statement errors prevented编写的main.php文件。

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {    
    try {
        # check if all the params are set
        if (
            !empty($_POST['firstname']) && 
            !empty($_POST['lastname']) &&
            !empty($_POST['email'])
        ) {
            $firstname = htmlspecialchars(trim($_POST['firstname']));
            $lastname = htmlspecialchars(trim($_POST['lastname']));
            $email = htmlspecialchars(trim($_POST['email']));

            include_once 'db.php';

            $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");

            if (
                $stmt &&
                $stmt->bind_param("sss", $firstname, $lastname, $email) &&
                $stmt -> execute() 
            ) {
                echo "Yay! Inserted.";
            } else {
                throw new Exception("Error in MYSQLI Statement");   
            }
        } else {
            throw new Exception("Some data is not set");
        }
    } catch (Exception $e) {   
        die($e -> getMessage());
    }
} else { ?>

<form action="" method="post">
  First name:
  <input type="text" name="firstname">
   <br> Last Name:
   <input type="text" name="lastname">
    <br>Email:
   <input type="text" name="email">
  <input type="submit" value="Submit">
</form>
<?php } ?>

在插入数据库之前,字符串应为validated。在这里,我使用htmlspecialchars()来防止XSS,并使用trim()来删除不必要的空格。

谢谢。

答案 2 :(得分:0)

表单操作将调用t.php,但是您没有它! 在同一文件夹中创建两个文件:myHtml.html和t.php

myHtml.html

<html>
    <form action="t.php" method="post">
        First name:
        <input type="text" name="firstname">
        <br> Last Name:
        <input type="text" name="lastname">
        <br>Email:
        <input type="text" name="email">
        <input type="submit" value="Submit">
    </form>
</html>

t.php

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute
$stmt->execute();

$stmt->close();
$conn->close();