Guest User

Untitled

a guest
Nov 5th, 2018
533
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. <?php
  2.  
  3. $servername = "localhost";
  4. $username = "root";
  5. $password = "";
  6. $database = "test";
  7.  
  8. try {
  9.  
  10. $conn = new PDO("mysql:host=$servername;dbname=$database;charset=utf8", $username, $password);
  11. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  12.  
  13. } catch(PDOException $e) {
  14. echo "Connection failed: " . $e->getMessage();
  15. }
  16.  
  17. if (isset($_POST['submit'])) {
  18. $conn->exec("INSERT INTO products (`title`, `description`) VALUES ('".$_POST['title']."','" . $_POST['description']."')");
  19. }
  20.  
  21. $query = $conn->prepare("SELECT * FROM products");
  22. $query->execute();
  23. $products = $query->fetchAll(PDO::FETCH_ASSOC);
  24.  
  25. $query = $conn->prepare("SELECT count(id) AS total_products FROM products");
  26. $query->execute();
  27. $count = $query->fetchAll(PDO::FETCH_ASSOC);
  28.  
  29.  
  30. ?>
  31.  
  32. <!DOCTYPE html>
  33. <html>
  34. <head>
  35. <title>PHP MySQL</title>
  36. <meta charset="utf-8">
  37. </head>
  38. <body>
  39. <h3>Add new product</h3>
  40. <form action="index.php" method="post">
  41. <input type="text" name="title" placeholder="Title">
  42. <input type="text" name="description" placeholder="Description">
  43. <button type="submit" name="submit">Add</button>
  44. </form>
  45.  
  46. <div>
  47. <pre><?php
  48. foreach ($products as $product) {
  49. echo $product['id'] . ': ' . $product['title'] . ' ' . $product['price'] . "<br>";
  50. }
  51. ?></pre>
  52. </div>
  53. </body>
  54. </html>
Add Comment
Please, Sign In to add comment