I will share my best PHP class to help you connect to MySQL. It is easy to use (easier than the classic way). It is fast and it helps you if you forget to escape some strings before inserting or things like those.
If you use it please reference me, this site and my email address (as a comment in the code is fine
)
The 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 | <?php /** * mbe.ro * * @author Ciprian Mocanu <http://www.mbe.ro> <ciprian@mbe.ro> * @license Do whatever you like, just please reference the author * @version 1.56 */ class mysql { var $con; function __construct($db=array()) { $default = array( 'host' => 'localhost', 'user' => 'root', 'pass' => '', 'db' => 'test' ); $db = array_merge($default,$db); $this->con=mysql_connect($db['host'],$db['user'],$db['pass'],true) or die ('Error connecting to MySQL'); mysql_select_db($db['db'],$this->con) or die('Database '.$db['db'].' does not exist!'); } function __destruct() { mysql_close($this->con); } function query($s='',$rows=false,$organize=true) { if (!$q=mysql_query($s,$this->con)) return false; if ($rows!==false) $rows = intval($rows); $rez=array(); $count=0; $type = $organize ? MYSQL_NUM : MYSQL_ASSOC; while (($rows===false || $count<$rows) && $line=mysql_fetch_array($q,$type)) { if ($organize) { foreach ($line as $field_id => $value) { $table = mysql_field_table($q, $field_id); if ($table==='') $table=0; $field = mysql_field_name($q,$field_id); $rez[$count][$table][$field]=$value; } } else { $rez[$count] = $line; } ++$count; } if (!mysql_free_result($q)) return false; return $rez; } function execute($s='') { if (mysql_query($s,$this->con)) return true; return false; } function select($options) { $default = array ( 'table' => '', 'fields' => '*', 'condition' => '1', 'order' => '1', 'limit' => 50 ); $options = array_merge($default,$options); $sql = "SELECT {$options['fields']} FROM {$options['table']} WHERE {$options['condition']} ORDER BY {$options['order']} LIMIT {$options['limit']}"; return $this->query($sql); } function row($options) { $default = array ( 'table' => '', 'fields' => '*', 'condition' => '1', 'order' => '1' ); $options = array_merge($default,$options); $sql = "SELECT {$options['fields']} FROM {$options['table']} WHERE {$options['condition']} ORDER BY {$options['order']}"; $result = $this->query($sql,1,false); if (empty($result[0])) return false; return $result[0]; } function get($table=null,$field=null,$conditions='1') { if ($table===null || $field===null) return false; $result=$this->row(array( 'table' => $table, 'condition' => $conditions, 'fields' => $field )); if (empty($result[$field])) return false; return $result[$field]; } function update($table=null,$array_of_values=array(),$conditions='FALSE') { if ($table===null || empty($array_of_values)) return false; $what_to_set = array(); foreach ($array_of_values as $field => $value) { if (is_array($value) && !empty($value[0])) $what_to_set[]="`$field`='{$value[0]}'"; else $what_to_set []= "`$field`='".mysql_real_escape_string($value,$this->con)."'"; } $what_to_set_string = implode(',',$what_to_set); return $this->execute("UPDATE $table SET $what_to_set_string WHERE $conditions"); } function insert($table=null,$array_of_values=array()) { if ($table===null || empty($array_of_values) || !is_array($array_of_values)) return false; $fields=array(); $values=array(); foreach ($array_of_values as $id => $value) { $fields[]=$id; if (is_array($value) && !empty($value[0])) $values[]=$value[0]; else $values[]="'".mysql_real_escape_string($value,$this->con)."'"; } $s = "INSERT INTO $table (".implode(',',$fields).') VALUES ('.implode(',',$values).')'; if (mysql_query($s,$this->con)) return mysql_insert_id($this->con); return false; } function delete($table=null,$conditions='FALSE') { if ($table===null) return false; return $this->execute("DELETE FROM $table WHERE $conditions"); } } |
Example usage:
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | $connection_information = array( 'host' => 'localhost', 'user' => 'root', 'pass' => '', 'db' => 'test' ); $m = new mysql($connection_information); //simple and complex query (I recommend you use the select method of the class rather than this) $result = $m->query('SELECT * FROM `users`'); var_dump($result); //this will output an array like this: $array[$count][$table][$field] //simple execute command (I recommend using the delete and the insert and the update methods of the class) $result = $m->execute('DELETE FROM `pages` WHERE `id`=5'); var_dump($result); //returns true if ok and false if not //method to select (clean and beautiful) $result = $m->select(array( 'table' => 'users', 'condition' => 'active=1 AND type=1' )); var_dump($result); // Will output something like this: /* array (3) { [0] => array (1) { ['users'] => array (4) { ['id'] => int (5), ['name'] => string (7) "ciprian", ['active'] => int (1), ['type'] => int (1), ['email'] => string (14) "ciprian@mbe.ro" } }, [1] => ... } */ //you can also get only one row (and a simple array like this $array[$table_field]) $result = $m->row(array( 'table' => 'users', 'condition' => 'active=1 AND type=1' )); var_dump($m); //returns only the first row in an array arranged like this $array[$table_field] //or you can get only a field (for example you need the name of the user with id = 5) $name=$m->get('users','name','id=5'); var_dump($name); // Will output something like this: /* string (7) "ciprian" */ //you can also insert into the table $data = array( 'name' => 'ion', 'active' => 0, 'email' => 'ion@mbe.ro' ); $result = $m->insert('users',$data); var_dump($result); //returns true if ok and false if not //update the table (let's assume we have a pages table and we need to set the views of the page with + 1 $data = array( 'views' => array( 'views+1' ) ); $result = $m->update('pages',$data,'id='.$current_page_id); var_dump($result); //returns true if ok and false if not //PS: Notice I put the value of the views in another array. You can do that in the update as well as in the insert. If you put it like that, no mysql_real_escape_string will be called for that value when updating / inserting. //deletion is also possible $result = $m->delete('pages','id=5'); //deletes page with id 5 var_dump($result); //returns true if ok and false if not |




Fantastic. Thank you.
It would be great if you could show us how to loop over the select results
Hi, does the query function manages insert, update and select?;
I love your tutorial !
foreach ($result as $key)
foreach ($key as $key) {
echo $key["fieldname"];
}
good class, and good tutorial
thank you
Really nice one I’ll post some functions for anyone who wants to extend this class :
/**
*
* This function returns the field names of a table
*
*
* @param string $result the mysql resource pointer to a query
* @return returns a 2D array with the field names
*/
public function get_fields($result)
{
$row = $this->fetchAssoc($result);
if($row==TRUE)
return array_keys($row);
else
return false;
}
/**
* prevent sql injections
*
*/
public function prevent_injection($value) {
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote if not a number or a numeric string
if (!is_numeric($value)) {
$value = mysql_real_escape_string($value);
}
return $value;
}
Cool. Would sure come back to give more suggestions once I start using it.
this is a really a nice posing. i have my own blog and i really appreciate this as because i have used this classes and it really works a lot. It will increase the security and productivity as well.
i have a very simple class tutorial on the same topic. if you found this class quite turf to understand you can give a loot to my tutorial.
http://www.codingquery.com/php-mysql-connection-class-source-code
fantastic work thanx bro
in short tags, where do I need additional security from sql injection
e.g.
$data = array(
// have to escape this?
‘name’ => mysql_real_escape_string($var),
);
$result = $m->insert(‘users’,$data);
Nice Work, Thank you so much. This class it’s really helpfull and saves a lot of time. For those who wants to use the statement "group by" I added a single line for making this possible in select function:
function select($options) {
$default = array (
‘table’ => ”,
‘fields’ => ‘*’,
‘condition’ => ’1′,
‘order’ => ’1′,
‘limit’ => 100000,
‘groupby’ =>”
);
$options = array_merge($default,$options);
//modificacion group by
if($options['groupby']==”)
$sql = "SELECT {$options['fields']} FROM {$options['table']} WHERE {$options['condition']} ORDER BY {$options['order']} LIMIT {$options['limit']}";
else
$sql = "SELECT {$options['fields']} FROM {$options['table']} WHERE {$options['condition']} GROUP BY {$options['groupby']} ORDER BY {$options['order']} LIMIT {$options['limit']}";
return $this->query($sql);
I noticed that in any of your examples there is no order by/group by clause. Is there any reason you left support for that out of the class?
Never mind. I took a deeper look at the class file and figured it out