Reputation: 185
I am trying to send a value for an item in a MySQL table and increment its "availability" column by one.
A press of a button executes the following onclick function:
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 looks like this:
<?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>';
?>
I think this is generally correct, unfortunately I'm not getting a table update when I execute the code. I am 100% confident in the validation for the variable val
, and fairly confident with updateStuff()
, but I'm less sure if I'm handling the server-side stuff corecctly with putting $_GET
inside of response
tags.
EDIT: I have made the syntax correction given by asparatu, but the problem persists.
Upvotes: 1
Views: 182
Reputation: 4491
try this to update query:
$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);
}
Upvotes: 0
Reputation: 128
The update query is wrong.
$result = mysqli_query($db, "UPDATE inventory SET available = available + 1 WHERE item = " + $item);
Where are you getting the current number for available?
you need a select statement that queries the current item and get current available amount then you can add one to it.
$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);
That should work..
Upvotes: 1