Skip to main content

Kickass PHP Database Class for Simple Web Apps


Every time I need to build a quick web application in PHP, I always use this simple database class. I made some modifications and added more functions to the original source of this class.
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
class Database
    {
    var $Host     = "localhost";        // Hostname of our MySQL server.
    var $Database = "";         // Logical database name on that server.
    var $User     = "";             // User and Password for login.
    var $Password = "";
    var $Link_ID  = 0;                  // Result of mysql_connect().
    var $Query_ID = 0;                  // Result of most recent mysql_query().
    var $Record   = array();            // current mysql_fetch_array()-result.
    var $Row;                           // current row number.
    var $LoginError = "";
    var $Errno    = 0;                  // error state of query...
    var $Error    = "";
//-------------------------------------------
//    Connects to the database
//-------------------------------------------
    function connect()
        {
        if( 0 == $this->Link_ID )
            $this->Link_ID=mysql_connect( $this->Host, $this->User, $this->Password );
        if( !$this->Link_ID )
            $this->halt( "Link-ID == false, connect failed" );
        if( !mysql_query( sprintf( "use %s", $this->Database ), $this->Link_ID ) )
            $this->halt( "cannot use database ".$this->Database );
        } // end function connect
//-------------------------------------------
//    Queries the database
//-------------------------------------------
    function query( $Query_String )
        {
        $this->connect();
        $this->Query_ID = mysql_query( $Query_String,$this->Link_ID );
        $this->Row = 0;
        $this->Errno = mysql_errno();
        $this->Error = mysql_error();
        if( !$this->Query_ID )
            $this->halt( "Invalid SQL: ".$Query_String );
        return $this->Query_ID;
        } // end function query
//-------------------------------------------
//    If error, halts the program
//-------------------------------------------
    function halt( $msg )
        {
        printf( "
<strong>Database error:</strong> %s
n", $msg );
        printf( "<strong>MySQL Error</strong>: %s (%s)
n", $this->Errno, $this->Error );
        die( "Session halted." );
        } // end function halt
//-------------------------------------------
//    Retrieves the next record in a recordset
//-------------------------------------------
    function nextRecord()
        {
        @ $this->Record = mysql_fetch_array( $this->Query_ID );
        $this->Row += 1;
        $this->Errno = mysql_errno();
        $this->Error = mysql_error();
        $stat = is_array( $this->Record );
        if( !$stat )
            {
            @ mysql_free_result( $this->Query_ID );
            $this->Query_ID = 0;
            }
        return $stat;
        } // end function nextRecord
//-------------------------------------------
//    Retrieves a single record
//-------------------------------------------
    function singleRecord()
        {
        $this->Record = mysql_fetch_array( $this->Query_ID );
        $stat = is_array( $this->Record );
        return $stat;
        } // end function singleRecord
//-------------------------------------------
//    Returns the number of rows  in a recordset
//-------------------------------------------
    function numRows()
        {
        return mysql_num_rows( $this->Query_ID );
        } // end function numRows
//-------------------------------------------
//    Returns the Last Insert Id
//-------------------------------------------
    function lastId()
        {
        return mysql_insert_id();
        } // end function numRows
//-------------------------------------------
//    Returns Escaped string
//-------------------------------------------
    function mysql_escape_mimic($inp)
        {
        if(is_array($inp))
            return array_map(__METHOD__, $inp);
        if(!empty($inp) && is_string($inp)) {
            return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
        }
        return $inp;
        }
//-------------------------------------------
//    Returns the number of rows  in a recordset
//-------------------------------------------
    function affectedRows()
        {
            return mysql_affected_rows();
        } // end function numRows
//-------------------------------------------
//    Returns the number of fields in a recordset
//-------------------------------------------
    function numFields()
        {
            return mysql_num_fields($this->Query_ID);
        } // end function numRows
    } // end class Database
/* From: kjventura.com */
Simple Implementation
After configuring the database class, save the code above as database.php
Single Record
1
2
3
4
5
6
7
8
9
10
11
12
13
require_once("database.php");
$db = new Database();
$sql = "SELECT * FROM tbl_user WHERE userId='1' ";
$db->query($sql);
$db->singleRecord(); //call this if the query will only return a single row
echo $db->Record['userId']; // use the field name for example or;
echo $db->Record[0]; //use indexes
Multiple Records
1
2
3
4
5
6
7
8
9
10
11
12
13
require_once("database.php");
$db = new Database();
$sql = "SELECT * FROM tbl_user WHERE ";
$db->query($sql);
while($db->nextRecord()){
echo $db->Record['userId'];
}//will output all rows with the field of userId returned by the query
Other Functions
1
2
3
4
5
6
7
$db->lastId(); // Returns the primary key of the last inserted record
$db->numRows(); //Returns the number of rows in a recordset
$db->numFields(); //Returns the number of fields in a recordset
$db->mysql_escape_mimic($string); // Returns escaped string

Comments

Popular posts from this blog

Off-Page SEO – 7 Tips On How To Build BackLinks

Well a site cannot get expected traffic without doing seo in the world of completion. After introducing  on page seo . Now come back to introduce off page seo and basics of off page seo. As the word off page seo shows to do seo staying off from own page. Means to optimize a website from other sources. In simple a short we can define it as link building or creating backlinks. Off page seo helps site to get rank in search engines.   Fairly Off page seo is to create and build backlinks from several of ways. Off page seo is a hungriness of backlinks.”There so many ways to do off page seo or creating backlinks but now, let me show you how to build links to your pages: 1. Profile Pages Build Profile Pages in the top Social Media sites like: Google+ Profiles-           https://profiles.google.com            (A Must) Facebook Pages –     ...

August 6, 2017 CSE-PPT Professional Level - List of Passers (REGION XII)

August 6, 2017 CSE-PPT Professional Level  - List of Passers Civil Service Commission Regional Office No. 12 SOURCE: PRC ABALOS, ROMEO III G ABANG, CHRISTIAN MARK B ABAS, AMIRA A ABBA, BRYAN M ABDULADSIS, SAYEED MOHBEN K ABDULSATAR, SAHID M ABEAR, KRIZIA ANDREA Q ABELLON, SHIENA MAE F ABING, MARY SOL T ABOLENCIA, SEAN HOPE C ACIDO, DANIEL CARLO G ACUPAN, NONA MARIE P ADANG, SAIMA D ADELAN, MAILA LOUISA N ADVENTAJADO, CLYDELL S AGAD, LUCILLE ANGELIKKA DC AGAWA, YSA LOU S AGCARAO, APRIL BERNADETH P AGUILAR, RUTH D AGUJA, MARCO D AGURING, FROILAN J AJOC, LOVELL L AKIL, SAGUIRA M ALAMADA, SHAINETRA C ALAMAN, OMAR ADRIANNE P ALBARAN, GLORY GRACE C ALBRANDO, GERALDINE P ALCANTARA, KIMBERLY V ALCOBA, MARY ANN L ALCORDO, QUENNIE N ALDAVE, ANNABELLE JOY B ALLAGA, LOREN F ALLOSO, MERCY FE N ALMOJALLAS, JAN MARIE MAY J ALONZO, CHARMAINE KLAIRE A ALTIZO, ALEN JANE E ALURAN, ELLEN JANE C ALVAREZ, NEALL DOMINICK T AMAN, JOHN PAUL C AMANDE, JOEVEN A AMBAY, ARRIZ PAULA D AMER, ABJUHARY H AMINO, ...

Future Pinoy scientists, a Museum of Natural History

Michael Purugganan, when he was an elementary student at Union Science Elementary School in Malate, used to sneak into the National Science Development Board premises, where he would spend hours in a small museum.  "It just fascinated me. I just wanted to learn more about these things and what these people were doing there," Purruganan told GMA News Online.  "That was really what inspired me to become a scientist," said Purugganan, who is currently the Dean for Science at New York University and a world leader in evolutionary and ecological genomics.   With a new museum in the works, more young Filipinos may be inspired to become scientists. In a couple of years, the Philippines will have its own world class Museum of Natural History, showcasing endemic plants and animals that can be found in the country, according to a report on State of the Nation on January 23. Museums bridge the past and present, but the government believes these can also meet...