我还有一个关于连接到Mysql数据库的问题。
我有一个带有Tinymce在线文本编辑器的简单文本文档。在线我想用编辑器更改文本,将其保存到Mysql数据库,然后在线显示新文本。我有以下脚本,我从文件doAddContents.php中得到此错误:
警告:mysql_real_escape_string():第8行的/../doAddContents.php中的用户''@ localhost'(使用密码:NO)拒绝访问
警告:mysql_real_escape_string():无法在第8行的/../doAddContents.php中建立指向服务器的链接
我不知道我做错了什么。以下是脚本:
首先连接数据库的脚本:
db.php中:
<?php
function doDB() {
global $mysqli;
//connect to server and select database
$mysqli = mysqli_connect("localhost", "name", "pass", "db-name");
//if the connection fails, stop script execution
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
?>
doAddContents.php文件:
<?php
include("db.php");
doDB();
$h4_block = "Contents Saved!";
$elm1 = $_POST['elm1'];
$entity_elm1 = htmlentities($elm1);
$entity_elm1 = mysql_real_escape_string($entity_elm1);
$add_contents_sql = "UPDATE tinymce_contents SET `contents`=
'$entity_elm1', `modified`=now()";
$add_contents_res = mysqli_query($mysqli, $add_contents_sql)
or die(mysqli_error($mysqli));
//close connection to MySQL
mysqli_close($mysqli);
//create nice message for user
$display_block = "<p>The page has been successfully updated.</p>";
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<div>
<h4><?php echo $h4_block; ?></h4>
<?php echo $display_block; ?>
<a href="view.php">View Page!</a>
</div>
</body>
</html>
View.php文件:
<?php
include("db.php");
doDB();
$h4_block = "View Page!";
$get_contents_sql = "SELECT * FROM tinymce_contents";
$get_contents_res = mysqli_query($mysqli, $get_contents_sql)
or die(mysqli_error($mysqli));
if ($get_contents_res = mysqli_query($mysqli, $get_contents_sql)) {
//fetch associative array
while ($row = mysqli_fetch_assoc($get_contents_res)) {
$id = $row['id'];
$contents = $row['contents'];
$modified = $row['modified'];
//Draw the results
$view_block ="<p>ID: ".$id."</p>";
$view_block .="<b>Contents</b>:".html_entity_decode($contents);
$view_block .="<b>Modified</b>:".$modified."<br/>";
}
}
//close connection to MySQL
mysqli_close($mysqli);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<div>
<h4><?php echo $h4_block; ?></h4>
<?php echo $view_block; ?>
<a href="index.php">Back to Page Edit!</a>
</div>
</body>
</html>
答案 0 :(得分:1)
根据mysql_real_escape_string的文档。如果没有与mysql_connect()
打开连接,该函数将尝试创建一个mysql连接。
http://php.net/manual/en/function.mysql-real-escape-string.php
您不应该使用mysql_real_escape_string()
,而是使用mysqli_real_escape_string()