我正在尝试在我的主页上显示网站标题。此网站标题存储在名为mywebsite
的数据库和表settings
中。我想用input type text
的值来更新它。标题显示完美,但是当我在文本字段中写入内容并提交时,数据库不会更新。我认为我正在做的一切正确,我的页面上没有显示任何错误,但仍然无法正常工作。任何人都可以找出错误吗?
这是我的代码:
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
// Making connection
$con = mysqli_connect($host, $username, $password, $database);
// Making a sql query for "Website Title" and saving it in variable $query
$query = "SELECT * FROM settings WHERE NameOfSetting='Website Title'";
// Applying query
$result = mysqli_query($con, $query);
// Fetching data from database
$row = mysqli_fetch_array($result);
if (isset($_POST['submit'])) {
$title = $_POST['text'];
mysqli_query($con, "UPDATE settings SET TheSetting=$title WHERE NameOfSetting='Website Title'");
}
?>
<h1><?php echo $row['TheSetting']; ?></h1>
<form method="POST">
<input type="text" placeholder="Change the title" name="text">
<input type="submit" name="submit">
</form>
编辑:当我在字段中输入任何数字然后提交并刷新它工作正常但它只能处理数字而不是字母表。我不知道为什么?
答案 0 :(得分:1)
这一行:
SET TheSetting=$title
$title
需要用引号括起来:
SET TheSetting='$title'
旁注:您可能还想更改此行(作为安全预防措施):
$title = $_POST['text'];
为:
$title = mysqli_real_escape_string($con,$_POST['text']);
答案 1 :(得分:0)
你可以随时进行某种错误检查。即使用或死亡(mysqli_error);
$con = mysqli_connect($host, $username, $password, $database)or die(mysqli_error);
这至少可以让你了解你的问题。每次连接,查询或关闭数据库时都使用此错误检查方法。
答案 2 :(得分:0)
使用此代码可以解决您的问题。
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
// Making connection
$con = mysqli_connect($host, $username, $password, $database)or die(mysqli_error());
// Making a sql query for "Website Title" and saving it in variable $query
$query = "SELECT * FROM settings WHERE NameOfSetting='Website Title'";
// Applying query
$result = mysqli_query($con, $query);
// Fetching data from database
$row = mysqli_fetch_array($result);
if (isset($_POST['submit'])) {
$title = $_POST['text'];
mysqli_query($con, "UPDATE settings SET TheSetting='".$title."' WHERE NameOfSetting='Website Title'");
}
?>
<h1><?php echo $row['TheSetting']; ?></h1>
<form method="POST">
<input type="text" placeholder="Change the title" name="text">
<input type="submit" name="submit">
</form>
答案 3 :(得分:0)
尝试
mysqli_query($con, "UPDATE settings SET TheSetting='$title' WHERE NameOfSetting='Website Title'");