我是web開發中的新手。我正在檢查如何使用PHP將數據從表單更新到服務器中的數據庫。我似乎能夠連接到數據庫,但無法更新數據。無法使用PHP在MySQL數據庫中插入數據
窗體的HTML:
<html>
<head>
<title>Experiment with php and db</title>
</head>
<body>
<form name="form1" id="form1" method="post" action="formact.php">
<p><input type="text" name="fname" placeholder="first name"/></p>
<p><input type="text" name="lname" placeholder="last name"/></p>
<p><textarea name="words" placeholder="Enter what you think"></textarea></p>
<p><button type="submit"></button></p>
</form>
</body>
這裏是formact.php
<?php
$name=$_POST['fname']." ".$_POST['lname'];
$ta=$_POST['words'];
$con = mysql_connect();
$msg="status 0";
if (!$con)
{
$msg="db connect failed";
die('Could not connect: ' . mysql_error());
}
if ($con)
$msg="db connected";
mysql_select_db("php_test",$con);
$success=mysql_query("INSERT INTO news (title, blog_entry) VALUES ('$name','$ta')");
mysql_close($con);
?>
<html>
<head>
<title>Form with php</title>
</head>
<body>
<?php
echo $name."<br/>";
echo $ta."<br/>";
echo $msg."<br/>";
if(!$success)
echo "DB update failed..";
?>
</body>
</html>
我得到的回聲$msg=="db connected"
和!success==true
。 你能指出我在哪裏做錯了嗎?
一些DB用戶被限制在更改內容。因此,首先檢查您的用戶是否具有寫入權限。 –
你應該至少使用'mysqli_ *'。如果你正試圖學習PHP,避免過時的API,例如'mysql_ *' – BenM
如果(!$ success)回顯「數據庫更新失敗..」,則更改。到if(!$ success)echo'Error:'.mysql_error();並重新運行,以便我們可以看到錯誤是什麼。 –