我希望用户点击一个按钮删除de div,并且为了不再显示在他的网页上我想更改我的数据库中的值,以便网页知道它已被删除而不再出现在&#中39;新闻源&#39 ;.它确实删除了div,但没有对DB做任何事情。
JS代码:
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
//for IE
if(window.ActiveXObject) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//THIS object is the heart of AJAX for users using IE
}
catch(e) {
alert("Connection Error1");
xmlHttp = false;
}
}
else {
try {
xmlHttp = new XMLHttpRequest(); //THIS object is the heart of AJAX
}
catch(e) {
alert("Connection Error2");
xmlHttp = false;
}
}
if(!xmlHttp) {
alert("Connection Error");
}
else {
return xmlHttp;
}
}
function deletePreview(id){
xmlHttp.open("GET","entOfferDeletePreview.php?id=" + id + "&t=" + Math.random(),true);
xmlHttp.send(null);
alert(id);
}
function removeDummy(id) {
var elem = document.getElementById(id);
elem.parentNode.removeChild(elem);
}
PHP
<?php
include('classes/dbConnection.php');
$link = new dbConnection;
$id = $_GET['id'];
$query = 'UPDATE entoffers SET preview = 1 WHERE id = "$id" ';
$res = $link->query($query);
if($res){
echo '<script>alert("done");</script>';
}
?>
答案 0 :(得分:3)
错误位于PHP文件的$query = 'UPDATE entoffers SET preview = 1 WHERE id = "$id" ';
第8 行:
来自php.net:
与double-quoted和heredoc语法不同,变量和特殊字符的转义序列在单引号字符串中出现时不会被展开
这意味着单引号文本被视为字符串,因此您的查询将字面上UPDATE entoffers SET preview = 1 WHERE id = "$id"
,不会影响任何行。
Double quote文本将通过替换和处理它们的值来解析变量。
如果您的id
字段是整数,请使用:
$query = "UPDATE entoffers SET preview = 1 WHERE id = " . $id;
如果它是varchar(例如&#39; db1_42 &#39;),则使用:
$query = "UPDATE entoffers SET preview = 1 WHERE id = '" . $id; . "';
注意:查询中的数据应正确转义为prevent SQL injections。
答案 1 :(得分:1)
这是粗略单文件实现。它使用预准备语句来缓解注入攻击,它实现了从数据库添加/删除的能力,所有数据库事务都是通过ajax请求完成的。
我已经使用函数来处理Ajax工作,因此您可以轻松地逐个启动几个,在请求完成时收到通知,或者如果失败则收到消息(如果出现错误,您可以轻松更改此信息以便调用您由于传递给回调的ajax对象与发出请求时创建的对象相同,因此您可以访问responseText,responseXML等等成员。在这个例子中,我没有对结果做任何事情 - 虽然你可以看到一个用于打印它的注释掉的行。
注意:
■它将在与脚本相同的文件夹中创建文件test.db.sqlite
。
■您需要进行最小的更改才能使用mysql。此代码改编自一些在免费主机上运行的,不包含SQlite3 PDO驱动程序,并且对MySql dbs的数量有限制(基本上,数据库数量仅受磁盘空间的限制,而不是人为的低数字,旨在诱使你购买primo计划)。 想到的更改是(1)在前几行中与db建立连接的方式,以及(2)从查询中获取结果集的代码。 PDO允许将行检索为对象 - 我将它们作为带有命名键的数组返回。鉴于你想要实现的任务,我猜#2与你无关,但仍然值得一提。
希望它有所帮助! :)
oneFile.php (名称很重要,因为它会向自己发出ajax请求)
<?php
/*
ensure database and table exist
*/
$dbFilename = "test.db.sqlite3";
$sqlDb = new SQLite3($dbFilename);
$queryStr = "CREATE TABLE if not exists "
. "`sampleTable` "
. "(`id` INTEGER PRIMARY KEY AUTOINCREMENT, `comment` TEXT ); ";
$sqlDb->query($queryStr);
/*
do the db insert/delete and then exit (without producing any output)
*/
if ( isset($_POST['submit']) == true )
{
$rawData = $_POST['submit'];
$parsedData = json_decode( $rawData );
$newComment = $parsedData->comment;
$query = $sqlDb->prepare("insert into `sampleTable` (comment) values (:newComment)");
$query->bindParam(":newComment", $newComment);
$query->execute();
printf("comment successfully added");
exit;
}
else if (isset($_POST['delete']) == true)
{
$rawData = $_POST['delete'];
$parsedData = json_decode( $rawData );
$removeId = $parsedData->id;
$query = $sqlDb->prepare("delete from `sampleTable` where id = :idToRemove");
$query->bindParam(":idToRemove", $removeId);
$query->execute();
printf("comment successfully deleted");
exit;
}
/*
Otherwise, just display the html - the remaining code in _this_ php block
only contains utility functions.
*/
function getResultArray( $sqlResult )
{
$resultArray = array();
while ($curRow = $sqlResult->fetchArray(SQLITE3_ASSOC))
{
$j = $sqlResult->numColumns();
$resultRow = array();
for ($i=0; $i<$j; $i++)
{
$resultRow[ $sqlResult->columnName($i) ] = $curRow[$sqlResult->columnName($i)];
}
$resultArray[] = $resultRow;
}
return $resultArray;
}
function addCommentSelectorOrMessage($stringSelectorId)
{
global $sqlDb; // declared as global so we access the variable defined on line 6 of this file.
$queryStr = "select * from sampleTable order by id asc";
$sqlResult = $sqlDb->query($queryStr);
$resultArray = getResultArray( $sqlResult );
$nResults = count($resultArray);
if ($nResults != 0)
{
printf("<select id='%s'>\n", $stringSelectorId);
for ($i=0; $i<$nResults; $i++)
{
printf("<option value='%d'>%s</option>\n", $resultArray[$i]['id'], $resultArray[$i]['comment'] );
}
printf("</select>\n");
}
else
printf("No database entries yet..<br>\n");
}
?>
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
function allByClass(className){return document.getElementsByClassName(className);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('addBtn').addEventListener('click', onAddBtn, false);
byId('delBtn').addEventListener('click', onDelBtn, false);
}
function onAddBtn()
{
var newComment = byId('commentInput').value;
var params = { comment: newComment };
myAjaxPost("oneFile.php", "submit", JSON.stringify(params), onCommentAddedOrDeleted);
}
function onDelBtn()
{
var commentId = byId('commentSelList').value;
var params = { id: commentId }; //new Object();
myAjaxPost("oneFile.php", "delete", JSON.stringify(params), onCommentAddedOrDeleted);
}
function onCommentAddedOrDeleted(ajax)
{
//alert(ajax.responseText);
if (ajax.responseText.length != 0)
alert(ajax.responseText);
window.location.reload();
}
function myAjaxGet(url, callback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
callback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
}
ajax.open("GET", url, true);
ajax.send();
}
function myAjaxPost(url, phpPostVarName, data, callback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
callback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(phpPostVarName+"=" + encodeURI(data) );
}
</script>
</head>
<body>
<h3>Add new comment</h3>
<input id='commentInput'/> <button id='addBtn'>Add comment to DB</button>
<br>
<h3>Saved comments</h3>
<?php addCommentSelectorOrMessage('commentSelList'); ?><button id='delBtn'>Delete</button>
<div id='ajaxResponseTgt'></div>
</body>
</html>