Increment with a button

Hello everybody !

I am currently making a little store page and I would like to have a button which, when is clicked, will add +1 to my quantity field in my database.

I am totally new to PHP and do not know if this is even possible, can anyone help me please ?

It is possible. Are you intending this to be on an admin / staff page?

To do it, you’d first have to get the current quantity from the database (assuming you’re using an ID) then add one and then store the result.

[php]$id = 2;
$result = mysql_query(‘SELECT quantity FROM some_table WHERE some_table.id="’ . $id . ‘"’);

if(mysql_num_rows($result) == 1) {

$row = mysql_fetch_array($result);
$qty = $row[‘quantity’];

mysql_query(‘UPDATE some_table SET some_table.quantity="’ . ($qty + 1) . ‘" WHERE some_table.id="’ . $id . ‘"’);

} else {

echo 'Failed to find item with ID of ', $id;

}[/php]

Hello and thanks for your help :slight_smile:

I honestly do not even understand what I am doing at the moment, I have been copy-pasting and stuff has been working so far. I do know what I’m doing in my database, but just not about the PHP.

Do you want my code so you can understand better or explain what your code does ? I am a total noob unfortunately :confused:

My table has an ID, a product and a quantity, those three are the fields. Could you explain how the button is linked to the PHP code ? All I have found on Internet was actually a code that ran by itself as soon as the page loaded :confused:

i think you want to update quantity in database when button is clicked. this could be done by a simple function which is called every time when button is clicked

[php]

// quantity update process can be done by calling
// below function when button is clicked
function update_quantity($product_id)
{
$result = mysql_query(‘SELECT quantity FROM product_basket WHERE productid="’ . $product_id . ‘"’);
if(mysql_num_rows($result) == 1) {
$row = mysql_fetch_array($result);
$qty = $row[‘quantity’];
mysql_query(‘UPDATE product_basket SET quantity = "’ . ($qty + 1) . ‘" WHERE productid ="’ . $product_id . ‘"’);
} else {
//If button is clicked first time for product than it would add new entry to product basket table with productid and quantity as 1
mysql_query(“INSERT INTO product_basket (productid, quantity) VALUES (1,1)”);
}
}

[/php]

i hope this will be useful for you.

Sponsor our Newsletter | Privacy Policy | Terms of Service