php mysql插入表工作一次,不能再工作了吗?

时间:2013-12-21 05:23:36

标签: php html mysql sql

StackOverflow专业人士。我遇到了一些障碍。我只是想为我的目录创建一个简单的添加站点功能,我能够创建查询,运行我的程序,并在我的表中添加一列没有问题。但后来我尝试添加一个条件,告诉我我的记录是否成功添加。当我这样做时,我运行它,我的if语句运行“else”意味着它没有添加我的记录,从那里我无法再添加记录。我已经删除了那个条件,但无济于事。每当我运行我的页面并将所有内容添加到文本字段时,就不会再添加任何记录。

这是我的代码......

<html>
<body>


<?php 
$user_name = "root";
$password = "";
$database = "mydirectory"; // name of database
$server = "127.0.0.1";
$Sitetbl = "tbl_mydirectory";
//define the variables sent from the form
//if form has been posted, do this
if ($_SERVER["REQUEST_METHOD"] == "POST")
 {
  $genre = trim($_POST["genre"]);
  $site = trim($_POST["siteadd"]);
  $name = trim($_POST["nameadd"]);

//connecting to database
$db_handle = mysql_connect($server, $user_name, $password);

//creating a query to add site
$addSQLQuery = "INSERT INTO $Sitetbl (Genre,Site_Address, Site Title)
VALUES ('$genre','$site','$name')";

$result=mysql_query($addSQLQuery,$db_handle);
}  
?>



<!-- send page to itself using server variable -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<h2>Add Site</h2>
Genre:<input type="text" name="genre"></br>
Http://<input type="text" name="siteadd"><br>
Name:<input type="text" name="nameadd"></br>
<input type="submit" value="Add">
</form>

</body>
</html>

和if语句(不再在我的代码中)是这个

if($result) 
{
echo "Website added successfully!";
}
else
{
echo "Error adding website. Please check fields.";
}

这是我的程序的底部,正好在PHP声明关闭的地方。

2 个答案:

答案 0 :(得分:3)

您必须尝试修改此代码。因为你错过了“mysql_select_db”行。

<?php 
$user_name = "root";
$password = "";
$database = "mydirectory"; // name of database
$server = "127.0.0.1";
$Sitetbl = "tbl_mydirectory";
//define the variables sent from the form
//if form has been posted, do this
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
 $genre = trim($_POST["genre"]);
 $site = trim($_POST["siteadd"]);
 $name = trim($_POST["nameadd"]);

 //connecting to database
 $db_handle = mysql_connect($server, $user_name, $password) or die('Host Connection Error');

 mysql_select_db($database,$db_handle) or die('DB Connection Error');

 //creating a query to add site
 $addSQLQuery = "INSERT INTO $Sitetbl (Genre,Site_Address, Site Title)
 VALUES ('$genre','$site','$name')";

 $result=mysql_query($addSQLQuery,$db_handle) or die('Query Error');
 }  
 ?>

 <!-- send page to itself using server variable -->
 <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
 <h2>Add Site</h2>
 Genre:<input type="text" name="genre"></br>
 Http://<input type="text" name="siteadd"><br>
 Name:<input type="text" name="nameadd"></br>
 <input type="submit" value="Add">
 </form>

 </body>
 </html>

答案 1 :(得分:-1)

首先,您不应该使用mysql扩展,您应该使用新安装的PHP上新的mysqli(MySQL Improved)扩展。以下一行:

$result=mysql_query($addSQLQuery,$db_handle);

应该读(mysqli扩展名):

$result=mysqli_query($db_handle,$addSQLQuery);

希望这有帮助!