无法获取php mysqli while语句来发布[重复]

t40tm48m  于 2023-10-15  发布在  PHP
关注(0)|答案(4)|浏览(111)

此问题已在此处有答案

How to include a PHP variable inside a MySQL statement(5个答案)
3天前关闭。
我是php的新手,我一直在尝试获得一个表单来将值发布到数据库中。

  • 我已经成功地连接到数据库,因为我可以从表中提取值并在HTML中显示它们。
  • 我相信mysqli_query是正确的,因为我可以用示例替换$变量,它们可以工作并发布。
  • 然而,我似乎找不到如何插入$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>
thigvfpy

thigvfpy1#

尽量不要将id放入查询中,我假设此列是自动递增的。你也应该把变量如下所示

$query = "INSERT INTO Friends (Name, Description) 
                   VALUES ('".$name."', '".$desc."')";

注意:如果你能告诉我们什么数据存储在您的数据库中,这将是有帮助的

mcdcgff0

mcdcgff02#

试图取代

$query = "INSERT INTO Friends (ID, Name, Description)
VALUES ('NULL', $name, $desc)";

$query = "INSERT INTO Friends (ID, Name, Description)
VALUES ('NULL', {$name}, {$desc})";

您可以使用PDO,而不是将SQL语句编写为字符串

nwsw7zdq

nwsw7zdq3#

我不得不把desc用反引号括起来,这是MySQL所说的“这是一个变量名”,因为desc是一个关键字。如果您将列名改为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

7y4bm7vi

7y4bm7vi4#

https://github.com/yamen110/Solution_get_not_statments.git
这段代码将解决您的问题,但您必须使ID成为自动递增列。
为此:
1.转到数据库
1.去table(“朋友”)
1.点击结构
1.点击更改ID
1.点击A_I

相关问题