gpt4 book ai didi

php - 我无法将 HTML 表单与 MySQL 数据库连接

转载 作者:行者123 更新时间:2023-11-30 00:43:43 24 4
gpt4 key购买 nike

我正在尝试构建一个表单,然后使用 PHP 将其连接到我的 SQL 数据库来填充表格。但我无法连接数据库。当我按提交时,会打开一个空白页面..并且没有任何内容插入我的数据库中。请问你能帮我吗?有什么问题吗?

这是我的 HTML 表单

<html>
<head>
<title> Futja e te dhenave nepermjet nje forme </title>
<style type = "text/css">
body { background-color: #cfd0f9 }
h2 { font-family: arial, sans-serif;
color: blue }
h3 {font-color: yellow}

.error {color: #FF0000;}
</style>
</head>
<body>

<h1><center>please enter data</center></h1>

<p> <span class="error">* please fill these fields.</span> </p>
<form method="post" action="insert.php">

<strong> Emri:&nbsp &nbsp &nbsp &nbsp &nbsp </strong> <input type="text" name="fname" />
<span class="error">* <?php echo $fnameErr;?></span>
<br>

<strong> Mbiemri:&nbsp &nbsp </strong> <input type="text" name="lname" />
<span class="error">* <?php echo $dtlErr;?></span>
<br>


<input type="submit" name= "shto" value="Add"/>

</form>

</body>
</html>

这是insert.php。我的数据库名为 test,表名为 user。该表包含三列:User_id, fname,lname

<html>
<body>

<?php
$con = mysql_connect('127.0.0.1','root','');
if (!$con)
{
die('The connection is not possible: ' . mysql_error());
}


if(empty($_POST['fname']))
die ('Name is empty'. mysql_error());
mysql_select_db("test", $con);
if(empty($_POST['lname']))
die ('Last name is empty'. mysql_error());
mysql_select_db("test", $con);

$sql="INSERT INTO user(fname,lname)
VALUES
('$_POST[fname]','$_POST[lname]')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Successful insertion!!! ";

mysql_close($con)
?>
</body>
</html>

最佳答案

尝试添加一些消息,以便您知道代码必须像这样:

<html>
<body>

<?php
echo '<pre>Before Connect' . print_r($_POST, true) . '</pre>'; // display the $_POST array

$con = mysql_connect('127.0.0.1','root','');
if (!$con)
{
die('The connection is not possible: ' . mysql_error());
}

echo 'After Connect';

mysql_select_db('test', $con);

echo 'Database selected';

if(empty($_POST['fname'])) die ('Name is empty'. mysql_error());

if(empty($_POST['lname'])) die ('Last name is empty'. mysql_error());

$sql = "INSERT INTO user(fname,lname) VALUES ('$_POST[fname]','$_POST[lname]')";

echo "<br>$sql</br>";

if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "Successful insertion!!! ";

mysql_close($con)
?>
</body>
</html>

现在,如果屏幕上没有显示任何内容,则说明出现了非常严重的错误。请记住 die() 命令也应该写入浏览器。

关于php - 我无法将 HTML 表单与 MySQL 数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21563713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com