Guest User

Untitled

a guest
Dec 12th, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.11 KB | None | 0 0
  1. <?php
  2. $db_host = "YOUR_DB_HOST";
  3. $db_name = "YOUR_DB_NAME";
  4. $db_user = "YOUR_DB_USER";
  5. $db_pass = "YOUR_DB_PASS";
  6.  
  7. function sql($dbh,$s,$v=array()){ // USE PDO TO QUERY MYSQL DB
  8. $stmt = $dbh->prepare($s); // prepare statement
  9. if (!$stmt) die("Database error [prepare]"); // report errors
  10. foreach($v as $key => $val) $bind = $stmt->bindValue($key,strval($val)); // bind statement
  11. $exec = $stmt->execute(); // execute statement
  12. if (!$exec) die("Database error [execute]"); // report errors
  13. return $stmt; // return results
  14. }
  15.  
  16. $pdo = new PDO("mysql:host=$db_host;dbname=$db_name",$db_user,$db_pass); // open PDO connection to MySQL
  17. if (!$pdo) die("Database error [connect]"); // report errors
  18.  
  19. if(isset($_POST["chosen"])) $chosen=$_POST["chosen"]; // get the post element
  20. if(isset($chosen)){ // if any items are selected {
  21. foreach($chosen as $key => $val){ // for each item {
  22. $q = "insert into tbl_orders (item_code) values (:b_code)"; // insert SQL with placeholder
  23. $s = sql($pdo,$q,array(":b_code"=>$val)); // run the query with bind variable
  24. } // }
  25. echo "Inserted the following product codes: ".implode(",",$chosen); // show which were inserted
  26. } // }
  27. ?>
  28. <!DOCTYPE html>
  29. <html>
  30. <body>
  31. <form action="#" method="post">
  32. <table>
  33. <tr><th>Code</th><th>Name</th><th>Description</th></tr>
  34. <?php
  35. $q = "select item_code, item_name, item_desc from tbl_products order by item_code"; // select SQL
  36. $s = sql($pdo,$q); // run the query
  37. while($r=$s->fetch(PDO::FETCH_ASSOC)) { // for each result {
  38. echo "<tr>"; // create row
  39. echo "<td><input type='checkbox' name='chosen[]' value='".$r["item_code"]."'/></td>"; // show checkbox
  40. echo "<td>".$r["item_code"]."</td>"; // show code
  41. echo "<td>".$r["item_name"]."</td>"; // show name
  42. echo "<td>".$r["item_desc"]."</td>"; // show desc
  43. echo "</tr>"; // end row
  44. } // }
  45. ?>
  46. </table>
  47. <input type="submit" value="Go" />
  48. </form>
  49. </body>
  50. <?php
  51. $pdo = null; // close PDO connection
  52. ?>
Add Comment
Please, Sign In to add comment