我是php新手,我一直试图让表单发布到数据库的值。
我已成功连接到数据库,因为我可以从表中提取值并在HTML中显示它们。
我相信mysqli_query是正确的,因为我可以用示例替换$ variables并且它们可以工作并发布。
但是,我似乎无法找到如何插入$ name和$ desc变量的正确组合我尝试过$ name,'$ name'和'$ _POST [friendname]。我错过了什么?
<?php
include 'includes/connect.php';
$name = $_POST[friendname];
$desc = $_POST[desc];
//WRITE TO DATABASE
if(!$_POST) {
echo "Form info: " . $name . " " . $desc;
echo "<br />Use the form below to add a new person! <br /><br />";
}
else {
$query = "INSERT INTO Friends (ID, Name, Description) VALUES ('NULL', $name, $desc)";
mysqli_query($sql, $query);
echo "<br />You've added " . $name . "<br /><br />";
}
$result = mysqli_query($sql,"SELECT * FROM Friends");
while($row = mysqli_fetch_array($result)) {
echo "<strong>" . $row['Name'] . "</strong> - " . $row['Description'];
echo "<br>";
}
?>
<p><strong>Add a new person to the database</strong></p>
<!-- FORM -->
<form name="addform" action="index.php" method="post">
Name: <input type="text" name="friendname" /><br />
Description: <input type="text" name="desc" /><br />
<input type="submit" name="submit" label="submit" />
</form>
答案 0 :(得分:1)
尽量不将id放入查询中,我假设此列是自动递增的。 你还应该把变量放在下面显示
$query = "INSERT INTO Friends (Name, Description)
VALUES ('".$name."', '".$desc."')";
注意:如果您可以向我们展示数据库中存储的数据,那将会有所帮助
答案 1 :(得分:0)
尝试替换
$query = "INSERT INTO Friends (ID, Name, Description)
VALUES ('NULL', $name, $desc)";
到
$query = "INSERT INTO Friends (ID, Name, Description)
VALUES ('NULL', {$name}, {$desc})";
而不是将SQL语句写为字符串,您可以使用PDO
答案 2 :(得分:0)
因为desc
是一个关键字,所以我必须将desc
包含在反对引用中,这是MySQL代表的“这是一个变量名称”。如果您将列名更改为description
,则会让您的生活更轻松。
PDO作为大多数PHP安装的标准配置,确实使事情变得更加容易。
<?php
$pdo = new PDO("mysql:host=localhost;dbname=mysql", "user", "password");
if (isset($_POST))
{
$name = $_POST['friendname'];
$desc = $_POST['desc'];
echo "Form info: " . $name . " " . $desc;
// WRITE TO DATABASE
$sql = "INSERT INTO Friends(friendname, `desc`) VALUES (:fn, :d)";
$query = $pdo->prepare($sql);
$query->execute(array(':fn'=>$name, ':d'=>$desc));
echo "<br />You've added " . $name . "<br /><br />";
die;
}
?>
<p>Use the form below to add a new person!</p>
<p><strong>Add a new person to the database</strong></p>
<form name="addform" action="index.php" method="post">
Name: <input type="text" name="friendname" /><br />
Description: <input type="text" name="desc" /><br />
<input type="submit" name="submit" label="submit" />
</form>
这里有一个合理的例子来执行“SELECT *”: How to fetch row with PDO