Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $servername = "localhost";
- $username = "root";
- $password = "";
- $database = "test";
- try {
- $conn = new PDO("mysql:host=$servername;dbname=$database;charset=utf8", $username, $password);
- $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- } catch(PDOException $e) {
- echo "Connection failed: " . $e->getMessage();
- }
- if (isset($_POST['submit'])) {
- $conn->exec("INSERT INTO products (`title`, `description`) VALUES ('".$_POST['title']."','" . $_POST['description']."')");
- }
- $query = $conn->prepare("SELECT * FROM products");
- $query->execute();
- $products = $query->fetchAll(PDO::FETCH_ASSOC);
- $query = $conn->prepare("SELECT count(id) AS total_products FROM products");
- $query->execute();
- $count = $query->fetchAll(PDO::FETCH_ASSOC);
- ?>
- <!DOCTYPE html>
- <html>
- <head>
- <title>PHP MySQL</title>
- <meta charset="utf-8">
- </head>
- <body>
- <h3>Add new product</h3>
- <form action="index.php" method="post">
- <input type="text" name="title" placeholder="Title">
- <input type="text" name="description" placeholder="Description">
- <button type="submit" name="submit">Add</button>
- </form>
- <div>
- <pre><?php
- foreach ($products as $product) {
- echo $product['id'] . ': ' . $product['title'] . ' ' . $product['price'] . "<br>";
- }
- ?></pre>
- </div>
- </body>
- </html>
Add Comment
Please, Sign In to add comment