Reputation: 23
I'm a bit of a noob at php/sql (well all languages in general), I am trying to get an sql command to run on the click of a html button.
The sql command that I am trying to run is UPDATE supplies SET quantity = quantity + 1 WHERE Id=1
This is what I have at the moment:
dp.php
<?php
$servername = "localhost";
$dbname = "tonor";
$username = "root";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
index.php
<!DOCTYPE html>
<html>
<head>
<?php
require_once 'db.php';
if(isset($_POST['data'])){
$sth = $conn->prepare("UPDATE supplies SET quantity = quantity + 1 WHERE Id=1");
$sth->execute();
}
?>
<title>Homepage</title>
<link rel="stylesheet" type="text/css" href="style/main.css">
</head>
<body>
<h1>testpage</h1>
<form method="POST" action="index.php">
<input type="submit" name="data" value="1"/>
</form>
Upvotes: 0
Views: 9814
Reputation: 29
I am answering on john's post.
The reason it executes every time you reload the page is because the browser resends the post data to the server. You need to use header() to redirect on post. Your code is not perfect but it works. You should organize it. Maybe place all database logic in a class. An example of redirection that works for this example.
<?php
if(isset($_POST['data']))
{
require 'db.php';
$sth = $conn->prepare("UPDATE supplies SET quantity = quantity + 1 WHERE Id=1");
$sth->execute();
header("Location: {$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']}");
die("Posted, now redirecting");
}
?>
Upvotes: 1
Reputation: 593
You should try this out, but you need to read, and practice further.
PDO manual: http://php.net/manual/en/book.pdo.php
It's a lot to look at, but just take a look at their examples to get an idea of how it works.
Read this as well to make it easier: https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
PHP is a server side language.
I any case, the following should be enough to get you started.
<?php
$servername = "localhost";
$dbname = "databasename";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $conn;
?>
<!DOCTYPE html>
<html>
<head>
<?php
require 'db.php';
if(isset($_POST['data'])){
$sth = $conn->prepare("UPDATE supplies SET quantity = quantity + 1 WHERE Id=1");
$sth->execute();
}
?>
<title>Homepage</title>
<link rel="stylesheet" type="text/css" href="style/main.css">
</head>
<body>
<h1>testpage</h1>
<form method="POST" action="">
<input type="submit" name="data" value="1"/>
</form>
</body>
</html>
Upvotes: 2