Paragraph -6ren">
gpt4 book ai didi

PHP SQL 一次更新多行

转载 作者:行者123 更新时间:2023-11-29 12:11:34 25 4
gpt4 key购买 nike

我陷入了项目的一个非常关键的部分,需要一些帮助 - 但是我似乎陷入了 PHP/SQL 语法,无法让查询工作。

HTML 代码:

<form name="homepage" method="POST" action="" >
<p>Page Title</p>
<input id="pagetitle" type="text" name="home_title" value="<?php select_text("SELECT fieldcontent FROM content WHERE name='home_title'", "fieldcontent") ?>"/>
<p>Paragraph</p>
<textarea id="paragraph" name="home_text"><?php select_text("SELECT fieldcontent FROM content WHERE name='home_text'", "fieldcontent") ?> </textarea>
<h1>Images</h1>
<div id="image">
<?php select_image("SELECT * FROM `image` WHERE image_cat_id = 8"); ?>
</div>
<button name="homesavebtn" id="home-save-btn" type="submit">Save Updates</button>
</form>

PHP 代码 - 选择数据

function select_text($sql, $echo) {
include 'connect.php';

$result = $conn->query($sql);
if ($result->num_rows > 0);
while ($row = $result->fetch_assoc()) {
echo $row[$echo];
$conn->close();
}
}

PHP 代码 - 更新

if ($_POST) {
if (isset($_POST['homesavebtn'])){
$home_title = (isset($_POST['home_title']) ? $_POST['home_title'] : null);
$home_text = (isset($_POST['home_text']) ? $_POST['home_text'] : null);

include 'connect.php';

$sql = "INSERT INTO content(name, fieldcontent) VALUES ('home_title', '$home_title') ON DUPLICATE KEY UPDATE fieldcontent = '$home_title'";
$sql .= "INSERT INTO content(name, fieldcontent) VALUES ('home_text', '$home_text') ON DUPLICATE KEY UPDATE fieldcontent = '$home_text'";

if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "" . $sql . "<br>" .mysqli_error($conn);
}
$conn->close();

}
}

出现以下错误:

INSERT INTO content(name, fieldcontent) VALUES ('home_title', 'Mosta Cycling Club') ON DUPLICATE KEY UPDATE fieldcontent = 'Mosta Cycling Club'INSERT INTO content(name, fieldcontent) VALUES ('home_text', '') ON DUPLICATE KEY UPDATE fieldcontent = '' You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO content(name, fieldcontent) VALUES ('home_text', '') ON DUPLICATE KE' at line 1

最佳答案

您可以使用VALUES来获取您在更新部分中使用的新值。另外,如果您使用 preparebind_param 您将防止 SQL 注入(inject):

$mysqli = new mysqli('host', 'user', 'password', 'db');

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$stmt = $mysqli->prepare("INSERT INTO content(name, fieldcontent)
VALUES ('home_title', ?), ('home_text', ?)
ON DUPLICATE KEY UPDATE fieldcontent = VALUES(fieldcontent)");

$stmt->bind_param('ss', $home_title, $home_text);
$stmt->execute();

关于PHP SQL 一次更新多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30580271/

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