PHP MySQL无法解释的空值 - 如何在一个记录中插入所有值?

时间:2010-12-05 21:11:11

标签: php mysql null html-table

我有这个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 Details</title>
</head>
<body>
    <h3> Insert Your Name</h3>
    <form action="form1.php" method="post">
    First Name: <input type="text" name="fname"><br>
       Last Name: <input type="text" name="lname"><br>
    E-mail:  <input type="text" name="mail"><br>
            <input type="Submit" value="Submit" name="Submit">
    </form>
</body>
</html>

转发到此PHP脚本以处理表单:

form1.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 (fname) VALUES ('".$_POST[fname]."')"; 
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
$query = "INSERT INTO table1 (lname) VALUES ('".$_POST[lname]."')"; 
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
$query = "INSERT INTO table1 (mail) VALUES ('".$_POST[mail]."')"; 
$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>First Name</TH>";
    echo "</TR>";    
while ($row = mysql_fetch_array($result))
     {
echo "<TR>";
echo "<TD>", $row['fname'], "</TD><TD>",
$row['lname'], "</TD><TD>",
$row['mail'], "</TD>";
echo "</TR>";  
     }
    echo "</TABLE>";
    mysql_close($connection);
?>

现在,出于某种原因,当我插入这些值时:

First Name: Wide
Last Name: Blade

我在MySQL表中获得了很多NULL值。

所以我的问题是:如何在同一条记录中插入所有这些值,所以我在表中没有得到这些NULL记录?

1 个答案:

答案 0 :(得分:2)

insert将新记录(行)添加到数据库中 - 您只想执行一次insert语句。

INSERT INTO table1(fname, lname, mail) VALUES ($fname, $lname, $mail);

更新:此外 - 您需要通过转义输入或使用预准备语句来防止sql注入。