Advertisement
Guest User

Untitled

a guest
Aug 26th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. <?php
  2. // HelloName.class.php
  3. // Prompt for a name on command line and save it to MySQL.
  4.  
  5. // All of this leading junk is for the exmaple.
  6.  
  7. // Requires an existing MySQL database named 'hello_name'.
  8. // In that database there must be an existing table called 'names'.
  9. // That table must have one row: 'name' (e.g. VARCHAR(255)).
  10. // Username and password on the MySQL database as follows:
  11. $mysql_user = 'hello-name-user';
  12. $mysql_pass = 'helloNaMEpaSS';
  13.  
  14. // This uses the class below, optionally you could skip the CLI:
  15. $default = new HelloName($mysql_user, $mysql_pass);
  16. $default->get_name_from_cli_prompt();
  17. // $default->set_name('Douglass Hoffstadter');
  18. $default->respond_with_name_on_cli();
  19. $default->prepare_db_statement();
  20. if ($default->db_statement_execute()) {
  21. print("Alright, we saved your name!\n");
  22. } else {
  23. print("Ruh roh, that's a bug!\n");
  24. }
  25.  
  26. class HelloName {
  27. protected $mysqli;
  28.  
  29. // Signed in to the database with full priviledges use these commands to set up:
  30. // mysql> CREATE DATABASE hello_name;
  31. // mysql> USE hello_name;
  32. // mysql> CREATE TABLE names (name VARCHAR(255));
  33. // mysql> CREATE USER 'hello-name-user'@'localhost' IDENTIFIED BY 'helloNaMEpaSS';
  34. // mysql> GRANT ALL ON names.* TO 'hello-name-user'@'localhost';
  35.  
  36. public $user_name;
  37. protected $database_statement;
  38.  
  39. function __construct($mysql_user='', $mysql_pass='') {
  40. $this->mysqli = new mysqli("localhost", $mysql_user, $mysql_pass, "hello_name");
  41. }
  42. // Get user's name from command line prompt:
  43. function get_name_from_cli_prompt() {
  44. $this->user_name = readline('Please enter your name: ');
  45. }
  46.  
  47. function set_name($name) {
  48. $this->user_name = $name;
  49. }
  50.  
  51. // Show them what you've got:
  52. function respond_with_name_on_cli() {
  53. print("Hello, $this->user_name. Let's put your name in the database.\n");
  54. }
  55.  
  56. // Now let's prepare the database statement, avoiding MySQL injection:
  57. function prepare_db_statement() {
  58. $this->database_statement = $this->mysqli->prepare('INSERT INTO names (name) VALUES(?)');
  59. $this->database_statement->bind_param('s', $this->user_name);
  60. }
  61.  
  62.  
  63. // Finally, let's try to execute that insert:
  64. function db_statement_execute() {
  65. if ($this->database_statement->execute()) {
  66. return True;
  67. } else {
  68. return False;
  69. }
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement