-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.php
113 lines (72 loc) · 2.18 KB
/
db.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
define("SERVER", "localhost");
define("DB", "comic-unstable");
define("USR", "root");
define("PWD", "fbgn9251");
class comicDbHandler{
public $con;
public function __construct($server, $db, $user, $pwd){
//conects to a database, sets $self->con as connection link
$con =mysql_connect($server, $user, $pwd);
if(!$con) {
die('Could not connect: ' .mysql_error());
}
$db_selected = mysql_select_db($db, $con);
if (!$db_selected){
die ("Can\'t use test_db : " . mysql_error());
}
$this->con = $con;
}
public function __destruct(){
mysql_close($this->con);
}
public function close(){
mysql_close($this->con);
}
public function retrieve_val_at_id($id){
//returns the value at a given id as an array
$sql = "SELECT * from comics WHERE id=".$id;
$result = (mysql_query($sql, $this->con));
$array=mysql_fetch_array($result);
return $array;
}
public function retrieve_max_id(){
//returns the last id in a db as an int
$sql = "SELECT max(id) from comics";
$result = (mysql_query($sql, $this->con));
$array=mysql_fetch_array($result);
return (int)$array[0];
}
public function add_comic($title, $url, $author){
//Inserts a comic at the end, and returns id at of that comic as an int
$id= $this->retrieve_max_id()+1;
$sql = "INSERT INTO comics VALUES ('$id','$title', '$url', '$author')";
$result = mysql_query($sql, $this->con);
return (int)$id;
}
public function delete_comic($id){
$sql = "Delete FROM comics WHERE id='$id'";
$result = mysql_query($sql, $this->con);
}
public function count(){
$sql = "SELECT * FROM comics";
$result = mysql_query($sql, $this->con);
return (int)mysql_num_rows($result);
}
public function rehash(){
//store everything in an array
for($i=1;$i<=$this->retrieve_max_id();$i++){
if( $this->retrieve_val_at_id($i) != ''){
$array[$i]=$this->retrieve_val_at_id($i);
}
}
//delete everything
for($i=1;$i<=$this->retrieve_max_id();$i++){
$this->delete_comic($i);
}
//insert everything to db
foreach ($array as $comic) {
$this->add_comic($comic['title'], $comic['url'], $comic['author']);
}
}
}