August 29, 2011 – 12:31 pm
Problem: I need to bring up usability by making a static class to connect to MySQL database with PHP
This is just an usual case where you need to bring in the object-oriented to help you solve worlds problems!
A long time ago i wrote this class to help me handle my database connections, and here i am to share it with the web.
Solution: class SQL
First, let us focus on the usage of the class (so called black-box unit):
First, as always you have some global variables which contain database info:
1
2
3
4
5
| //DB info, required by class SQL
$DBHost = "localhost";
$DBUser = "Dagelic";
$DBPassword = "12345678";
$DBDatabase = "MyDatabase"; |
Before we proceed: why is the class static? Well, it seems to me that one doesn't often need connections to multiple databases, so i made the class static, and simple load it into my project at the beginning, which lets me use it wherever and whenever i want to. You can make the class dynamic your self in a minute!
The usage
Below is the code which we use to:
- Connect to database.
- Execute some no-return query
- Execute a standard select query
- Show up results
- Close connection
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| //connects to database using globals mentiones above
SQL::Init();
//no-return method EQuery
SQL::EQuery("INSERT INTO 'posts' ('PostTitle', 'PostText') VALUES ('This is my title', 'Text text text Text text text Text text text Text text text')");
SQL::EQuery("DELETE FROM posts WHERE posts.PostID = 5");
SQL::EQuery("UPDATE posts SET PostText = CONCAT(PostText, " old") WHERE PostID < 10");
//returns result in array, NULL if none found - method Query
$ResArray = SQL::Query("SELECT * FROM posts");
if ($ResArray != NULL)
foreach($ResArray as $Res) {
echo "<p><strong>" . $Res['PostTitle'] . "</strong></p>";
echo "<p>" . $Res['PostText'] . "</p>";
}
else
echo "<p>No posts!</p>";
SQL::Close(); |
Some advanced features of static SQL connect class
- You can use $QSuccess boolean class variable to check if your last SQL query was successfull
- You can set $EchoQueryOnError boolean class variable to tell the class to echo SQL query in case of an error
- You can always access last queried query string by class variable $QueryString
- You can monitor if your class ever failed to execute some query by setting $MailErrors to 'true' and setting $MailAddress to your mail address
- The Query() method returns array of results which you only have to go foreach through
Finally the class code:
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
| /**
* @author AnteDD - www.antedagelic.com, dagelic.com
* 2011
*/
class SQL
{
public static $Connection = NULL;
//tells you if last query was successfull
public static $QSuccess = false;
//set to true if you want to echo query string on error
public static $EchoQueryOnError = false;
public static $QueryString;
//set to true if you want to mail query string on error to $MailAddress
public static $MailErrors = false;
private static $MailAddress = "me@example.com";
//connects to db, picks out database
public static function Init() {
global $DBHost;
global $DBUser;
global $DBPassword;
global $DBDatabase;
if (!(self::$Connection = mysql_connect($DBHost,
$DBUser,
$DBPassword))
){
echo "Error connecting to DB";
}
//default db charset - change for others
mysql_set_charset("utf8", self::$Connection);
if (!mysql_select_db($DBDatabase, self::$Connection)){
echo "Error connecting to DB";
}
}
//mails query string to a target e-mail
public static function MailError($Query){
mail(self::$MailAddress,
"SQL ERROR",
date("Y-m-d, h:s") . " " . $Query,
'From: ' . self::$MailAddress . "\r\n" .
'Reply-To: ' . self::$MailAddress . "\r\n");
}
//closes mysql connection
public static function Close() {
mysql_close(self::$Connection);
}
//Executes Query - returns nothing (INSERT, DELETE, UPDATE, CREATE...)
public static function EQuery($QueryString) {
self::$QueryString = $QueryString;
if (!mysql_query($QueryString)){
echo "Error executing query!<br/>";
if (self::$MailErrors) self::MailError($QueryString);
if (self::$EchoQueryOnError)
echo $QueryString;
self::$QSuccess = false;
}
else
self::$QSuccess = true;
}
//executes SELECT Query, returns array of results
public static function Query($QueryString){
$TotalResult = array();
self::$QueryString = $QueryString;
if (!($TmpResult = mysql_query($QueryString))){
if (self::$MailErrors) self::MailError($QueryString);
echo "Error executing query!";
if (self::$EchoQueryOnError)
echo $QueryString;
self::$QSuccess = false;
}
else
{
while ($Top = mysql_fetch_array($TmpResult))
{
$TotalResult[] = $Top;
}
self::$QSuccess = true;
}
if (count($TotalResult) == 0) return NULL;
return $TotalResult;
}
} |
Thats it! If you have any questions or suggestions for this article, you can e-mail me at / a d a g e l i c (e t) g m a i l . c o m /, or simply comment below!
August 25, 2011 – 1:08 pm
Problem: I need more than one jQuery version on my web page
Working on one of my projects, i used gray admin back-end theme, which has a great user notification system called ‘jQuery message plugin’ created by Peter Viszt, which runs only on one of the older versions of jQ (1.3.2). The thing is i had to install a jQuery UI time picker as well, which doesn’t run on 1.3.2.
Solution: $ noConflict
jQuery developers have thought this might happen, so they enabled programmers to be able to instance 2 jQuery objects. Since i lost quite some time handling this problem, let me guide you through the usage of .noConflict:
- Load the old version of jQuery first.
- Assign the jQuery object to another variable using jQuery.noConflict().
- Load the new version of jQuery.
1
2
3
4
5
| <script charset="utf-8" type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
oldjq = jQuery.noConflict(true);
</script>
<script charset="utf-8" type="text/javascript" src="js/jquery-1.5.1.js"></script> |
So what did we accomplish now?
From now on, when ever we want to use new version of jQuery, we start the usual syntax:
1
2
3
| $('#myid').myFun();
//or
jQuery('#myid').myFun(); |
But in case we want to use the old version of jQuery instead, we do it through the oldjq object:
1
| oldjq('#myid').myFun(); |
Now all this is great, but one other problem might happen! Since jQuery plugin and script developers usually use simple the $ object when calling jQuery, all our plugins could simply use the new version of jquery and ignore oldjq object. One way is to go through the plugin script and rename every $ or jQuery object into oldjq (which could be a lot of work since find-replace routine won’t work in most cases), but the other one is to simply change what $ means.
In case the plugin we are using is written properly its source starts something like this:
1
2
3
| (function(a){//})(jQuery);
//or
(function($) {})(jQuery); |
Here the $ or a argument (or any else) are representing the jQuery object used inside the plugin). The jQuery in the parentheses is actualy the default argument. So if we change that to oldjqeverything should be all right!
1
2
3
| (function(a){//})(oldjq);
//or
(function($){})(oldjq); |
And for the end, simple way to use any other object as jQuery object is to simply assign it to another variable like this:
And now we can use it:
1
| myOwnJQ("#myid").hide(); |
Thats it!