使用AJAX更新MySQL表

时间:2015-01-10 06:20:39

标签: php mysql ajax

我正在尝试为MySQL表中的项目发送一个值,并将其“可用性”列增加一个。

按一个按钮执行以下onclick功能:

function updateStuff() {

// Data validation for string variable val 
// coordinating to one of the items in the SQL table

var xmlHttp = false;

if(window.ActiveXObject){  
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
    xmlHttp = new XMLHttpRequest();
}

if(!xmlHttp)
    alert("Error : Cannot create xmlHttp object");
else{
    if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4){
        xmlHttp.open("GET","update.php?val=" + val, true);
        xmlHttp.send(); 
    }
    else{
      setTimeout(updateStuff,1000);
      }
}

}

update.php看起来像这样:

<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';

echo '<response>';
$item = $_GET['val'];
echo 'You selected ' . $item;

$server = "localhost";
$user = "root";
$pass = "";
$datab = "checkout";

// Connect to database
$db = mysqli_connect($server, $user, $pass, $datab);

// Check connection
if (mysqli_connect_errno()){
echo "Could not connect to database: " . mysqli_connect_error();
}

$results = mysqli_query($db,"SELECT * FROM inventory WHERE item = " . $item);
$available = $results['available'] + 1;
$result = mysqli_query($db, "UPDATE inventory SET available = " . $available . " WHERE item = " + $item);

// Close connection 
mysqli_close($db);

echo '</response>';

?>

我认为这通常是正确的,遗憾的是,当我执行代码时,我没有得到表更新。我对变量val的验证完全有信心,对updateStuff()非常有信心,但是我不太确定我是否正在通过放置{{1}来核心地处理服务器端的东西} $_GET标签内部。

编辑:我已经做了asparatu给出的语法修正,但问题仍然存在。

2 个答案:

答案 0 :(得分:1)

更新查询错误。

$result = mysqli_query($db, "UPDATE inventory SET available = available + 1 WHERE item = " + $item);

您从哪里获得当前可用的号码?

你需要一个select语句来查询当前项并获得当前可用数量,然后你可以添加一个。

$results = mysqli_query($db,"SELECT * FROM inventory WHERE item = " . $item);
$available = $results['available'] + 1;

$result = mysqli_query($db, "UPDATE inventory SET available = " . $available . " WHERE item = " . $item);

那应该有用..

答案 1 :(得分:0)

尝试此更新查询:

$result = "UPDATE inventory SET available = "' .$available. '" WHERE item = "' .$item. '"";    
if (mysqli_query($db, $result)) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . mysqli_error($db);
}