Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // HelloName.class.php
- // Prompt for a name on command line and save it to MySQL.
- // All of this leading junk is for the exmaple.
- // Requires an existing MySQL database named 'hello_name'.
- // In that database there must be an existing table called 'names'.
- // That table must have one row: 'name' (e.g. VARCHAR(255)).
- // Username and password on the MySQL database as follows:
- $mysql_user = 'hello-name-user';
- $mysql_pass = 'helloNaMEpaSS';
- // This uses the class below, optionally you could skip the CLI:
- $default = new HelloName($mysql_user, $mysql_pass);
- $default->get_name_from_cli_prompt();
- // $default->set_name('Douglass Hoffstadter');
- $default->respond_with_name_on_cli();
- $default->prepare_db_statement();
- if ($default->db_statement_execute()) {
- print("Alright, we saved your name!\n");
- } else {
- print("Ruh roh, that's a bug!\n");
- }
- class HelloName {
- protected $mysqli;
- // Signed in to the database with full priviledges use these commands to set up:
- // mysql> CREATE DATABASE hello_name;
- // mysql> USE hello_name;
- // mysql> CREATE TABLE names (name VARCHAR(255));
- // mysql> CREATE USER 'hello-name-user'@'localhost' IDENTIFIED BY 'helloNaMEpaSS';
- // mysql> GRANT ALL ON names.* TO 'hello-name-user'@'localhost';
- public $user_name;
- protected $database_statement;
- function __construct($mysql_user='', $mysql_pass='') {
- $this->mysqli = new mysqli("localhost", $mysql_user, $mysql_pass, "hello_name");
- }
- // Get user's name from command line prompt:
- function get_name_from_cli_prompt() {
- $this->user_name = readline('Please enter your name: ');
- }
- function set_name($name) {
- $this->user_name = $name;
- }
- // Show them what you've got:
- function respond_with_name_on_cli() {
- print("Hello, $this->user_name. Let's put your name in the database.\n");
- }
- // Now let's prepare the database statement, avoiding MySQL injection:
- function prepare_db_statement() {
- $this->database_statement = $this->mysqli->prepare('INSERT INTO names (name) VALUES(?)');
- $this->database_statement->bind_param('s', $this->user_name);
- }
- // Finally, let's try to execute that insert:
- function db_statement_execute() {
- if ($this->database_statement->execute()) {
- return True;
- } else {
- return False;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement