向mysql数据库输入数据的HTML表


HTML table inputting data to a mysql database

我试图得到一个表单输入数据到我的"mysql数据库",但我得到一个错误消息,而且它是输入一个空白的数据每次页面加载。

下面是我的代码:
    <form action="insert.php" method="post">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
// This is the connection to my database
$con = mysql_connect('127.0.0.1', 'shane', 'diamond89');
if (!$con){
die('Could not Connect: ' . mysql_error());
}
// This creates my table layout
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Delete</th>
</tr>";
// This selects which database i want to connect to
$selected = mysql_select_db("shane",$con);
if (!$con){
die("Could not select examples");
}
// This inserts new information to the Database
$query = "INSERT INTO test1 VALUES('id', '$name')";
$result = mysql_query($query);
if ($result){
echo("Input data is Successful");
}else{
echo("Input data failed");
}
// This chooses which results i want to select from
$result = mysql_query("SELECT `id`, `name` FROM `test1` WHERE 1");

// This outputs the information into my table
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . "[D]" . "</td>";
echo "</tr>";
}
echo "</table>";
// This closes my connection
mysql_close($con);
?>

错误信息如下:

(!)尖叫:错误抑制被忽略(!)注意:未定义变量:name在C:'wamp'www'sql_table.php的第36行调用堆栈

时间记忆功能位置

0.0006 250360{主要 }( ) ..' sql_table.php: 0

您正在尝试访问POST数据,因此您应该执行以下操作:

编辑:小心你放入数据库的数据。您应该使用一个现代的数据库API,或者,至少,转义您的数据(参见下面的代码)

<form action="insert.php" method="post">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
// Following code will be called if you submit your form
if (!empty($_POST['name'])) :
// This is the connection to my database
$con = mysql_connect('127.0.0.1', 'shane', 'diamond89');
if (!$con){
die('Could not Connect: ' . mysql_error());
}
// This creates my table layout
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Delete</th>
</tr>";
// This selects which database i want to connect to
$selected = mysql_select_db("shane",$con);
if (!$con){
die("Could not select examples");
}
// This inserts new information to the Database
$query = "INSERT INTO test1 VALUES('id', ''".mysql_real_escape_string($_POST['name'])."'')";
$result = mysql_query($query);
if ($result){
echo("Input data is Successful");
}else{
echo("Input data failed");
}
// This chooses which results i want to select from
$result = mysql_query("SELECT `id`, `name` FROM `test1` WHERE 1");

// This outputs the information into my table
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . "[D]" . "</td>";
echo "</tr>";
}
echo "</table>";
// This closes my connection
mysql_close($con);
endif;
?>