所以我在 php 中通过 mysqli 更新 mysql 表时遇到问题。
数据库连接和类:
<?php
class testDB extends mysqli {
private static $instance = null;
private $user = "tester";
private $pass = "tester01";
private $dbName = "testdb";
private $dbHost = "localhost";
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
private function __construct() {
parent::__construct($this->dbHost, $this->user, $this->pass, $this->dbName);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
parent::set_charset('utf-8');
}
public function verify_credentials ($username, $password){
$username = $this->real_escape_string($username);
$password = $this->real_escape_string($password);
$result = $this->query("SELECT 1 FROM users WHERE user_username = '" . $username . "' AND user_password = '" . $password . "'");
return $result->data_seek(0);
}
public function get_vitae() {
return $this->query("SELECT * FROM vitae");
public function update_vitae($text, $id) {
$text = $this->real_escape_string($text);
$this->query("UPDATE vitae SET vitae_text=".$text." WHERE vitae_id = ".$id);
}
}
?>
这是页面代码:
在标题上方,我们通过确保会话启动来检查登录;然后导入数据库类,其余部分在将表单重新提交到同一页面时调用:
<?php
session_start();
if (!array_key_exists("username", $_SESSION)) {
header('Location: index.php');
exit;
}
require_once("includes/db.php");
$vitae_empty = false;
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($_POST['text'] == "") {
$vitae_empty = true;
} else if ($_POST["text"]!="") {
testDB::getInstance()->update_vitae($_POST["text"], $_POST["id"]);
header('Location: manage.php' );
exit;
}
}
?>
在正文中(标题和 html 的其余部分通过“require_once”导入):
<section>
<div class="grid_3 header_line"><h2>Update for CV</h2></div>
<div class="grid_3">
<?php
$result = testDB::getInstance()->get_vitae();
$vitae = mysqli_fetch_array($result);
?>
<form name="editvitae" action="editvitae.php" method="POST">
<textarea name="text" rows="50" cols="100"><?php echo $vitae['vitae_text'];?></textarea><br/>
<?php if ($vitae_empty) echo "Please enter some text.<br/>";?>
<input type="hidden" name="id" value="<?php echo $vitae["vitae_id"];?>" /> <br/>
<input type="submit" name="savevitae" value="Save Changes"/>
</form>
</div>
<div class="grid_3">
<p><a href="manage.php">‹ back to management consol</a></p>
</div>
</section>
在'body'标签之后:
<?php mysql_free_result($result);?>
如您所见,这会从数据库中提取“简历”文本,然后将其循环到同一页面并进行更改以更新表格。它还检查“文本”框是否为空。
此代码适用于另一个应用程序;我不明白为什么它在这里不起作用。并且在您开始警告我有关注入和安全性之前,我已经删除了大部分内容,试图找到更新的问题。一旦我弄清楚了,它就会回来。
我试过剥离文本检查;不同的变量名;在更新数据库之前将帖子值转储到数组中;将帖子值放入静态变量中;检查我所有的拼写等...
我错过了一些东西,我觉得它会很简单。