HTML表单提交,数据未显示在数据库中

时间:2014-09-03 13:31:08

标签: php html mysql mysqli

我已经设置了一个非常简单的HTML表单,使用mysqli将First Name和Surname发布到MySQL数据库中,但是表单重定向到我的php脚本就好了,我没有错误,但是我的数据不是& #39; t显示在我的表格中。有线索吗?我有一段时间没有碰过这个,所以我有点抄袭一些大学项目,所以请纠正任何错误。

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Adam Short</title>
    <link href = "style.css" rel = "stylesheet" type = "text/css" media = "screen" />
</head>
<body>
    <div id = "wrapper">
        <form name="addAthlete" action="submit.php" method="POST">
            <label>First Name:</label>
            <input type="text" name="firstName" required="required"><br>
            <label>Surname:</label>
            <input type="text" name="surname" required="required"><br>
            <input type="submit" value="Submit">
        </form>
    </div>
</body>
</html>

PHP:

<?php
$mysql_host = "***";
$mysql_database = "***";
$mysql_user = "***";
$mysql_password = "***";  
con = mysqli_connect($mysql_host, $mysql_user, $mysql_password, $mysql_database);

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$firstName = mysqli_real_escape_string($con, $_POST["firstName"]);
$surname = mysqli_real_escape_string($con, $_POST["surname"]);

$sql = "INSERT INTO Athlete (FirstName, Surname) VALUES 
    ('$firstName','$surname')";

if (!mysqli_query($con, $sql)) {
  die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

1 个答案:

答案 0 :(得分:2)

为什么你的代码不能正常工作

在mysqli_connect中,您必须将database指定为第四个参数;你正在使用mysql_error而不是mysqli_error。

SQL注入

您的代码已打开sql injection。您可以使用mysqli_real_escape_string来解决此问题。

解决方案

替换

$con = @mysqli_connect($mysql_host, $mysql_user, $mysql_password)or die(mysql_error());

$firstName = $_POST["firstName"];
$surname = $_POST["surname"];

mysqli_select_db($con, $mysql_database)or die("cannot select database");

使用

$con = @mysqli_connect($mysql_host, $mysql_user, $mysql_password,$mysql_database)or die(mysqli_error($con));

$firstName = mysqli_real_escape_string($con,$_POST["firstName"]);
$surname = mysqli_real_escape_string($con,$_POST["surname"]);