Last active
August 29, 2015 14:14
-
-
Save nadirs/3082454b2413ef18afc7 to your computer and use it in GitHub Desktop.
Recursive table self-reference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MyDb { | |
protected $link = null; | |
public function __construct() { | |
$this->link = mysqli_connect('host', 'username', 'password', 'database'); | |
} | |
public function getCategoryByName($name) { | |
$stmt = $this->link->prepare('select * from categories where name like ?'); | |
$stmt->bind_param('s', $name); | |
$stmt->execute(); | |
$result = $stmt->get_result(); | |
return $result->fetch_object(); | |
} | |
public function getParent($cat) { | |
$stmt = $this->link->prepare('select * from categories where category_id like ?'); | |
$stmt->bind_param('i', $cat->parent_id); | |
$stmt->execute(); | |
$result = $stmt->get_result(); | |
$parent = $result->fetch_object(); | |
if ($parent->parent_id != 0) { | |
return $this->getParent($parent); | |
} | |
return $parent; | |
} | |
} | |
$db = new MyDb; | |
$name = 'Guerre Mondiali'; | |
$cat = $db->getCategoryByName($name); | |
$parent = $db->getParent($cat); | |
?> | |
<p> | |
La categoria principale di <?php echo $cat->name ?> (ID: <?php echo $cat->category_id ?>) è <?php echo $parent->name ?> (ID: <?php echo $parent->category_id ?>) | |
</p> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create table categories ( | |
category_id int not null AUTO_INCREMENT, | |
name varchar(100), | |
parent_id int not null, | |
primary key (category_id), | |
); | |
insert into categories(category_id, name, parent_id) values (0, '/', null); | |
insert into categories(category_id, name, parent_id) values (1, 'Storia', 0); | |
insert into categories(category_id, name, parent_id) values (2, '1900', 1); | |
insert into categories(category_id, name, parent_id) values (3, 'Guerre Mondiali', 2); | |
insert into categories(category_id, name, parent_id) values (4, 'Turismo', 0); | |
insert into categories(category_id, name, parent_id) values (5, 'Itinerari', 4); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment