我无法获取此AJAX代码来更新我的数据库。代码是onClick
将运行命令以更新数据库的图像
HTML:
<a>
<img class = "heart"
src = "images/heart.png"
onClick = "favUpdate(0,1)"
onMouseover = "this.src='images/heart_mo.png'"
onMouseout = "this.src='images/heart.png'"/>
</a>
Javascript代码:
function favUpdate(fav_up, id_up) {
$.ajax({
type: 'post',
url: 'includes/fav_update.php',
data: {favorite: fav_up, id: id_up},
success: function(output) {
alert('success, server says '
+ output
+ 'Variables passed are '+fav_up+' '+id_up);
},
error: function() {
alert('something went wrong, Favorite update failed');
}
});
}
PHP代码:
<?php
require_once('../Connections/main.php');
$fav_update = mysql_real_escape_string($_POST['favorite']);
$fav_id = mysql_real_escape_string($_POST['id']);
$query = "UPDATE projects SET favorite = $fav_update WHERE id = $fav_id";
mysql_query($query, $main);
?>
main.php
<?php
$hostname_main = "localhost";
$database_main = "test";
$username_main = "root";
$password_main = "";
$main = mysql_pconnect($hostname_main, $username_main, $password_main) or trigger_error(mysql_error(),E_USER_ERROR);
?>
有谁知道为什么它没有更新数据库以及为什么&#34;选项&#34;是不是要获取变量的数据?
答案 0 :(得分:1)
试试这个
<?php
require_once('../Connections/main.php');
$fav_update = mysql_real_escape_string($_POST['favorite']);
$fav_id = mysql_real_escape_string($_POST['id']);
$query = "UPDATE projects SET favorite = '".$fav_update."' WHERE id = '".$fav_id."'";
mysql_query($query, $main);
?>
答案 1 :(得分:0)
如果数据类型为字符串$fav_update
,则必须在VARCHAR,TEXT
附近放置单引号
$query = "UPDATE projects SET favorite = '$fav_update' WHERE id = $fav_id";
^ ^
从此处删除$main
并尝试
mysql_query($query);
答案 2 :(得分:0)
请尝试调试PHP(服务器端代码优先): -
<?php
require_once('../Connections/main.php');
$fav_update = mysql_real_escape_string($_REQUEST['favorite']);
$fav_id = mysql_real_escape_string($_REQUEST['id']);
$query = "UPDATE projects SET favorite = $fav_update WHERE id = $fav_id";
echo $query;
mysql_query($query, $main);
?>
使用$ _REQUEST而不是$ _POST,并通过创建类似http://localhost/filename.php?favorite=somevalue1&id=somevalue2
的网址
检查是否在DB中插入了插件,并通过打印来检查查询。
检查API后,请将$ _REQUEST更改回$ _POST
答案 3 :(得分:0)
将php脚本更改为:
<?php
require_once('../Connections/main.php');
$fav_update = mysql_real_escape_string($_POST['favorite']);
$fav_id = mysql_real_escape_string($_POST['id']);
$updateSQL = sprintf("UPDATE projects
SET favorite=%s
WHERE id=%s",
$fav_update,
$fav_id);
mysql_select_db($database_main, $main);
$Result1 = mysql_query($updateSQL, $main) or die(mysql_error());
?>
希望如果有人遇到同样的问题会有帮助