我陷入了项目的一个非常关键的部分,并希望得到一些帮助 - 但是我似乎陷入了PHP / SQL语法,无法让查询起作用。
HTML code:
<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(&#39; home_title&#39;,&#39; Mosta Cycling Club&#39;)ON DUPLICATE KEY UPDATE fieldcontent =&#39; Mosta Cycling Club&#39; INSERT INTO内容(名称,字段内容)值(&#39; home_text&#39;,&#39;&#39;)ON DUPLICATE KEY UPDATE fieldcontent =&#39;&#39; 您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以获得正确的语法,以便使用“INSERT INTO内容”(名称,字段内容)值(&#39; home_text&#39;,&#39;&#39;)ON DUPLICATE KE&#39;在第1行
答案 0 :(得分:1)
您可以使用VALUES
获取您在更新部分中使用的新值。此外,如果您使用prepare
和bind_param
,则会阻止SQL注入:
$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();
答案 1 :(得分:0)
你的第二个SQL语句被添加到你的第一个创建一个没有意义的长语句中。将它们分成两个不同的陈述。