gpt4 book ai didi

php脚本不会向mysql添加记录

转载 作者:行者123 更新时间:2023-11-29 07:44:47 24 4
gpt4 key购买 nike

第一个示例将数据添加到 mysql 数据库,没有任何问题。第二个代码块 - 我尝试使用变量不会。有人可以解释一下我哪里出错了吗?

<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);

问题代码:

<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;

$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);

最佳答案

*用 MySQLi 准备语句更新了答案,谢谢 @h2ooooooo

<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');

//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}

$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";

if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}

$stmt->bind_param('sss', $menu_name, $position, $visible);

if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}

$stmt->close();

我建议您通过网络查看许多教程,例如:

http://markonphp.com/simple-insert-mysqli/

http://www.sanwebe.com/2013/03/basic-php-mysqli-usage

关于php脚本不会向mysql添加记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28109445/

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