我刚刚安装了 xampp,但在将数据插入 MySQL 表时遇到问题。 我插入的数据没有出现在 phpmyadmin 中。我不确定是什么问题。
任何帮助将不胜感激,这是我的代码:
<html>
<head>
<title>Test</title>
<body>
<form action="test.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit"name="submit" value="submit"/>
</form>
<?php
$host ="localhost";
$username = "***";
$password = "***";
$database = "***";
$table ="persons";
$con = mysql_connect("localhost","***","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bucksbug_mesovot", $con);
$sql="INSERT INTO persons (firstname, lastname, age)
VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Data inserted";
mysql_close($con);
?>
</body>
</html>
最佳答案
虽然你真的应该切换到 PDO/mysqli 和带有绑定(bind)参数的准备语句以避免 sql 注入(inject)和破坏 sql 语句,如果你的变量包含引号,你也可能会遇到 PDO/mysqli 的问题:你的密码(更改它!)包含一个 $
。
请参阅 codepad 上的以下示例:
<?php
function test($var)
{
echo $var;
}
$test_var = "test$string";
test($test_var);
输出:
test
您将无法成功连接到数据库,因为您的密码永远不会正确。
改变:
"=c(p$zTTH2Jm"
到:
'=c(p$zTTH2Jm'
关于php - 向mysql表中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13400497/