PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
create table pizza ( id int primary key auto_increment, name varchar(64) ); insert into pizza (name) values ('Margarita'), ('Nepolitana'); create table menu ( category varchar(32), id int ); insert into menu values ('pizza', 1), ('pizza', 2);
Copy Clear
Copy Format Clear
<?php class Pizza { private $db; private $id = null; private $name; function __construct($db, $name) { $this->db = $db; $this->name = $name; } function name() { return $this->name; } function save() { if (is_null($this->id)) { $sql = "INSERT INTO pizza (name) VALUES (?);"; $stmt = $this->db->prepare($sql); $stmt->bind_param("s", $this->name); $stmt->execute(); $this->id = $stmt->insert_id; return $this->id; } } } class Menu { private $db; function __construct($db) { $this->db = $db; } public function get() { $sql = "SELECT * FROM menu JOIN pizza USING(id)"; $result = $this->db->query($sql); return $result->fetch_all(MYSQLI_ASSOC); } public function addPizza($pizza) { $sql = "INSERT INTO pizza (name) VALUES (?);"; $stmt = $this->db->prepare($sql); $name = $pizza->name(); $stmt->bind_param("s", $name); return $stmt->execute(); } } $menu = new Menu($mysqli); $pizza = $menu->get(); var_export($pizza); $pepperoni = new Pizza('Pepperoni'); $pepperony->save(); $menu->addPizza($pepperoni); $pizza = $menu->get(); var_export($pizza);
Show:  
Copy Clear