简体   繁体   English

PHP代码将空记录插入MySQL DB

[英]PHP Code Inserting Empty Records Into MySQL DB

My code inserts an empty record into the MySQL table "table1" instead of getting what inserted in the field "Name" in form1.html. 我的代码在MySQL表“table1”中插入一条空记录,而不是在form1.html中的“Name”字段中插入。 Any idea why it inserts an empty record instead of what the user entered in the field? 知道为什么它插入空记录而不是用户在字段中输入的内容吗?

form1.html form1.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd"
    >
<html lang="en">
<head>
    <title>Insert Your Name</title>
</head>
<body>
    <h3> Insert Your Name</h3>
    <form action="form1.php" method="post">
        <input type="text" name="Name">
            <input type="Submit" value="Submit" name="Submit">
    </form>
</body>
</html>

form.php form.php的

> <?php 
> $connection =
> mysql_connect("localhost","root","")
> or die ("Couldn't Connect To Server");
> $db = mysql_select_db("db1",
> $connection) or die ("Couldn't Select
> Database"); $query = "CREATE TABLE IF
> NOT EXISTS table1 (Name VARCHAR(20))";
> $result = mysql_query($query) or die
> ("Query Failed: " . mysql_error());
> $query = "INSERT INTO table1 (Name)
> VALUES ('$_post[Name]')"; $result =
> mysql_query($query) or die ("Query
> Failed: " . mysql_error()); $query =
> "SELECT * FROM table1"; $result =
> mysql_query($query) or die ("Query
> Failed: " . mysql_error());
>     echo "<TABLE BORDER = '1'>";
>     echo "<TR>";
>     echo "<TH>Name</TH>";
>     echo "</TR>";
>     
>     while ($row = mysql_fetch_array($result))
>     {
>         echo "<TR>";
>         echo "<TD>", $row['name'], "</TD>";
>         echo "</TR>";
>     }
>     echo "</TABLE>";
>     mysql_close($connection); ?>

Instead of 代替

$query = "INSERT INTO table1 (Name) VALUES ('$_post[Name]')";

Try this 尝试这个

$query = "INSERT INTO table1 (Name) VALUES ('" .
          mysql_real_escape_string($_post['Name'],$db) . "')";

Please change this 请改变这个

<input type="text" name="fname">


$query = "INSERT INTO table1 (Name)
 VALUES ('".mysql_real_escape_string($_POST[fname],$db)."')"; 
 $query = "INSERT INTO table1 (Name)
 VALUES ('{$_POST[Name]}')"; $result =
 mysql_query($query) or die ("Query
 Failed: " . mysql_error());

$_POST and $_GET are uppercase. $_POST$_GET是大写的。

change the display code to: 将显示代码更改为:

 while ($row = mysql_fetch_array($result))
     {
         echo "<TR>";
         echo "<TD>", $row['Name'], "</TD>";
         echo "</TR>";
     }
 " . ($_POST['Fname'] != "") ? $_POST['Fname'] : "No Name" ."

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM