我正在作为自己的第一个适当的网站工作,并且在使用特殊字符时无法查询数据库。我正在使用URI编码来帮助处理包含特殊字符(如“#”,“&”等)的查询。
基本上是这里发生的事情:我列出了数据库中的所有链接:
echo "<li><div class='trapez'><a onclick='getContent(this)';>{$row['title']}</a></div><br><br></li>";
然后,getContent(this)
将AJAX请求发送到PHP文件
function getContent(e) {
var name = encodeURIComponent(e.innerHTML);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("main").innerHTML = this.responseText;
}
};
xhttp.open("POST", "./getSideContent.php?q=" + name , true);
xhttp.send();
}
之后,PHP文件解码字符串并使用准备好的语句查询数据库以获取内容:
$q = urldecode($_REQUEST["q"]);
$stmt = $link->prepare("SELECT heading, content, created_at FROM tab_posts WHERE title= ?");
$stmt->bind_param("s", $title);
$title = $q;
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
现在,内容已准备好由网站显示,但似乎在使用&字符时,查询中出现了错误,并且该语句返回NULL。
这是的var_dump
,$_REQUEST['q']
其中包含“#”的查询结果
string(12) "Test post #2"
object(mysqli_result)#3 (5) {
["current_field"]=>
int(0)
["field_count"]=>
int(3)
["lengths"]=>
array(3) {
[0]=>
int(0)
[1]=>
int(3)
[2]=>
int(19)
}
["num_rows"]=>
int(1)
["type"]=>
int(0)
}
现在包含&:
string(15) "Test & post"
object(mysqli_result)#3 (5) {
["current_field"]=>
int(0)
["field_count"]=>
int(3)
["lengths"]=>
NULL
["num_rows"]=>
int(0)
["type"]=>
int(0)
}
顺便说一句,应该附加一个图像,显示数据库中存在该条目。
即使变量看起来正确,查询也将返回NULL,并且不会加载任何内容。这里发生了什么?我究竟做错了什么?另外,请不要给我“糟糕的代码”注释,这是我的第一个项目,我正在学习。
您需要始终为适当的显示环境准备输出。对于URL,您已正确完成。对于HTML,htmlspecialchars()
在输出的所有内容上使用:
<?php
$title = htmlspecialchars($row["title"]);
echo <<< HTML
<li>
<div class="trapez">
<a onclick="getContent(this)">$title</a>
</div>
<br/><br/>
</li>
HTML;
尽管更好的方法是传递有关行的数据库ID:
<?php
$id = htmlspecialchars($row["id"]);
$title = htmlspecialchars($row["title"]);
echo <<< HTML
<li>
<div class="trapez">
<a onclick="getContent($id)">$title</a>
</div>
<br/><br/>
</li>
HTML;
function getContent(id) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("main").innerHTML = this.responseText;
}
};
xhttp.open("GET", "./getSideContent.php?q=" + encodeURIComponent(id) , true);
xhttp.send();
}
然后,您的PHP可以更有效地进行搜索:
$stmt = $link->prepare("SELECT heading, content, created_at FROM tab_posts WHERE id = ?");
如果您只是在学习,则应该欢迎批评您的代码。您仅在此处分享了一些简短的摘要:
onclick
$_REQUEST
,这会导致草率的代码,例如...urldecode()
因为您的Web服务器已经做到了本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句