更改数据库值AJAX PHP JS
change db value AJAX PHP JS
我想让用户点击一个按钮来删除dediv,为了让它不再显示在网页上,我想更改数据库中的一个值,这样网页就知道它被删除了,不再出现在"新闻提要"中。它确实删除了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>';
}
?>
错误在PHP文件的$query = 'UPDATE entoffers SET preview = 1 WHERE id = "$id" ';
第8行中:
来自php.net:
与双引号和heredoc语法不同,当变量和特殊字符的转义序列出现在单引号字符串中时,它们将不会被扩展。
这意味着单引号文本被视为字符串,因此您的查询将是UPDATE entoffers SET preview = 1 WHERE id = "$id"
,不影响任何行
双引号文本将通过替换和处理变量的值来解析变量。
如果id
字段是整数,请使用:$query = "UPDATE entoffers SET preview = 1 WHERE id = " . $id;
否则,如果它是varchar(例如"db1_42"),请使用:$query = "UPDATE entoffers SET preview = 1 WHERE id = '" . $id; . "';
注意:应正确转义查询中的数据,以防止SQL注入。
这里有一个粗略的单文件实现。它使用准备好的语句来抵御注入攻击,实现了从数据库中添加/删除的能力,所有数据库事务都是通过对自身的ajax请求完成的。
我使用了一些函数来处理Ajax工作,所以你可以很容易地一个接一个地启动几个,在请求完成时得到通知,或者在失败时得到消息(如果发生错误,你可以很轻松地将其更改为调用你)。由于传递给回调的Ajax对象与发出请求时创建的对象相同,你可以访问responseText,responseXML等成员。在这个例子中,我对结果不做任何处理——尽管你可以看到一个注释行打印它
注:
■它将在与脚本相同的文件夹中创建文件CCD_ 6。
■使用mysql时,您需要进行最小的更改。这段代码改编自一些在免费主机上运行的代码,该主机不包括SQlite3 PDO驱动程序,并且对MySql dbs的数量有较低的限制(基本上,数据库的数量仅受磁盘空间的限制,而不是人为的低数量,旨在诱使您购买primo计划)。想到的变化是(1)在前几行中连接数据库的方式,以及(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>
- 在SVG地图上添加水的渐变,就像在谷歌地图(PHP/JS)中一样
- PHP/JS-EchoJs函数PHP curl发布后的通知
- FullCalendar backend PHP/JS to symfony 3
- 什么'是一个用于PHP+JS(extJS)开发的IDE,支持ctrl+click
- PHP/JS 文本差异
- 一个页面上有两个引导 php-js 表单
- Piwik:如何跨域(PHP/JS)跟踪访问者(用户ID)
- 使用php-js-msyql的实时更新消息系统
- 使用PHP/JS自动刷新Highcharts
- 如何为PHP/JS游戏制作倒计时/定时器
- node.js可以选择性地引入到用普通PHP/js/CSS/HTML构建的web应用程序中吗
- 用PHP/JS开发依赖表单字段的最佳方法
- 无法从数字中删除空白(PHP/JS)
- PHP/JS:动态Dropboxes和回显SELECTED值
- 更改数据库值AJAX PHP JS
- '套接字连接错误'在Aptana 3上调试PHP/JS时
- PHP/JS:用JS函数发布输入值,并通过PHP进行回显
- 在“onexit”或“onsubmit”之后,查询mysql并填充表单字段,而无需离开页面php js
- "Share-to-Facebook" html / php / js
- 从 PHP-JS 返回数组的计算的读取值