Advertisement
Garey

Radi

May 14th, 2019
555
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.90 KB | None | 0 0
  1. <?php
  2.  
  3. define('HOST', 'localhost');
  4. define('USER', 'root');
  5. define('PASS', '');
  6. define('NAME', 'radi');
  7. define('TABLE', 'books');
  8.  
  9. $result = null;
  10.  
  11. try {
  12.     $conn = new PDO('mysql:host='. HOST .';dbname='. NAME, USER, PASS);
  13.  
  14.     // errmode enabled
  15.     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  16.  
  17. } catch(PDOException $e) {
  18.     echo "Connection failed: " . $e->getMessage();
  19. }
  20.  
  21. if(isset($_POST['update'])) {
  22.     $title = htmlentities($_POST['title'], ENT_QUOTES, 'UTF-8');
  23.     $author = htmlentities($_POST['author'], ENT_QUOTES, 'UTF-8');
  24.  
  25.     $sql = 'UPDATE ' . TABLE . ' SET ' . (!empty($title) ? 'title = \'' . $title . '\'': '') . ' ' . (!empty($author) ? ', author = \'' . $author . '\'' : '') . ' WHERE id = ' . htmlentities($_GET['book'], ENT_QUOTES, 'UTF-8');
  26.  
  27.     $stmt = $conn->prepare($sql);
  28.     $stmt->execute();
  29.  
  30.     echo 'Successfully updated ' . $stmt->rowCount() .' rows!';
  31.  
  32. } else if(isset($_GET['book'])) {
  33.     $sql = 'SELECT * FROM books WHERE id = ' . htmlentities($_GET['book'], ENT_QUOTES, 'UTF-8');
  34.  
  35.     $stmt = $conn->prepare($sql);
  36.     $stmt->execute();
  37.    
  38.     $result = $stmt->fetchAll(PDO::FETCH_OBJ);
  39. }
  40.  
  41. ?>
  42.  
  43. <!DOCTYPE html>
  44. <html lang="en">
  45. <head>
  46.     <meta charset="UTF-8">
  47.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  48.     <meta http-equiv="X-UA-Compatible" content="ie=edge">
  49.     <title>Document</title>
  50. </head>
  51. <body>
  52.     <form method="post">
  53.         <label for="title">Title:</label><br>
  54.         <input type="text" name="title" id="title" value="<?= isset($result) ? $result[0]->title : "" ?>">
  55.  
  56.         <br><br>
  57.  
  58.         <label for="author">Author:</label><br>
  59.         <input type="text" name="author" id="author" value="<?= isset($result) ? $result[0]->author : "" ?>">
  60.        
  61.         <br><br>
  62.  
  63.         <button type="submit" name="update">Update Data</button>
  64.     </form>
  65. </body>
  66. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement