HTML表单定义插入到数据库

时间:2016-03-03 12:41:02

标签: php html mysql sql forms

我已创建HTML表单,点击提交按钮后,所有值都存储在 MySQL 数据库中。

我想创建编辑表单的能力。在点击Edit按钮表单后,我应该打开与新表单完全相同的内容,只需将所有已填充的值插入数据库。

我怎样才能实现这一目标?我想要将带有值的HTML代码存储到数据库(从<form></form>),但我不知道如果这是好主意而且根本不可能。

我的真实形式有超过100个字段,但简化它看起来像:

HTML表单:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.php" method="post">
    <p>
        <label for="firstName">First Name:</label>
        <input type="text" name="firstname" id="firstName">
    </p>
    <p>
        <label for="lastName">Last Name:</label>
        <input type="text" name="lastname" id="lastName">
    </p>
    <p>
        <label for="emailAddress">Email Address:</label>
        <input type="text" name="email" id="emailAddress">
    </p>
    <input type="submit" value="Submit">
</form>
</body>
</html>

要插入数据库的PHP代码:

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);

// attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// close connection
mysqli_close($link);
?>

1 个答案:

答案 0 :(得分:1)

您可以通过查询数据库中的所有值来实现这一目标:

$result = mysqli_query($link, "SELECT * from persons WHERE UserId = '$UserId'");
while ($row = mysqli_fetch_assoc($result)) {
  $first_name = $row['first_name']);
  $last_name = $row['last_name']);
  $email_address = $row['email_address']);
}

mysqli_close($link);

然后echo属性中的value

<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName" value=<?php echo $first_name ?>">

<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName" value=<?php echo $last_name ?>">

<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress" value=<?php echo $email_address ?>">