Coder Social home page Coder Social logo

php-mysql-class's Introduction

Important Notice

As of December 2014 I decided to upload the PHP MySQL Class I wrote a while back, and now use on a daily basis. It's PDO based (the mysql_* functions were due to be deprecated quite a while back now!).

The old version is still a part of this repo for now, and the readme is still available here.

PHP MySQL Class

This is a simple to use MySQL class that easily bolts on to any existing PHP application, streamlining your MySQL interactions.

Setup v2.0+

Include the class using composer as below:

composer require a1phanumeric/php-mysql-class

To use in your project, use the following:

use A1phanumeric\DBPDO;

$DB = new DBPDO('db_host', 'db_name', 'db_user', 'db_pass');

Setup Before v2.0


Firstly, define four constants for the host, database name, username and password:

define('DATABASE_NAME', 'my_database');

define('DATABASE_USER', 'username');

define('DATABASE_PASS', 'password');

define('DATABASE_HOST', 'localhost');

Then, simply include this class into your project like so:

include_once('/path/to/class.DBPDO.php');

Then invoke the class:

$DB = new DBPDO();

Direct Queries

To perform direct queries where you don't need to return any results (such as update, insert etc...), just do the following:

$DB->execute("UPDATE customers SET email = '[email protected]' WHERE username = 'a1phanumeric'");

That's the easiest way to use the class, but we should be utilising prepared statements now. This means no more escaping shizzle! To utilise prepared statements, just change the above code to the following:

$DB->execute("UPDATE customers SET email = ? WHERE username = ?", array('[email protected]', 'a1phanumeric'));

The class will invoke PDO's prepared statements and put the email and username in their place respectively, as well as escape all values passed to it. Note: You don't need to put the speechmarks in on the query, the ? is enough, and PDO will sort that out for you.

Fetching Rows

To perform select queries with this class, the syntax is similar to the above, but we have two functions we can utilise, fetch and fetchAll.

fetch simply returns one row, useful for getting a user by their ID for example. This returns an associative array and looks like:

$user = $DB->fetch("SELECT * FROM users WHERE id = ?", $id);

Now $user will contain an array of the fields for the row where there query matches. Oh, what's that? We didn't pass an array as the second parameter we just passed a single variable? That's cool, the class will treat a single variable the same as if you passed array($id). It's just a handy little time-saver.

fetchAll is used to fetch multiple rows, the parameters are similar, but the result returns an array of records:

$counties = $DB->fetchAll("SELECT * FROM counties");

The above will return a list of counties (in the UK) in my database like so:

[0] => Array
(
    [id] => 1
    [county] => London
)

[1] => Array
(
    [id] => 2
    [county] => Bedfordshire
)

[2] => Array
(
    [id] => 3
    [county] => Buckinghamshire
)

However, what if I want to loop over some raw data and check if the data matches the county name? To do that means either looping over these results every time, or shifting the key to the root dimension of the multi-dimensional array. However, if we pass a third variable, we can have that column as the key:

$counties = $DB->fetchAll("SELECT * FROM counties", null, 'county');

Note: I passed null as the second paramater as we're not passing any variables into the query to be escaped.

This will now return an array like the following:

[London] => Array
(
    [id] => 1
    [county] => London
)

[Bedfordshire] => Array
(
    [id] => 2
    [county] => Bedfordshire
)

[Buckinghamshire] => Array
(
    [id] => 3
    [county] => Buckinghamshire
)

So of course we could now do something like:

if(isset($counties[$raw_data['county_name']])){ //Do something }

License

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

php-mysql-class's People

Contributors

a1phanumeric avatar amalfra avatar argosback avatar behzad900 avatar cfilippe avatar cyrilcharlier avatar djmomo avatar gummibeer avatar hunter-dolan avatar jfcherng avatar king52311 avatar neurotroph avatar sajhu avatar thejwalker avatar woiweb avatar yeetim avatar ylu999 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-mysql-class's Issues

Update to use mysqli or PDO

in PHP v5.5 mysql functions are removed. Please revert back your commit because I thought it started working because of that silly thing. I spent all night before trying to figure it out and forgot somehow I really don't remember but the day after I went back to 5.4 because I found out other functions were removed. So now I realized that the real reason your script was removed was because I was using the wrong version. Please update you readme to note this as well if you don't plan on changing it. Here's the source http://www.php.net/mysql_query

(sorry for any spelling and grammar mistakes, its late and I'm exhausted. Read the source it'll explain all)

EDIT: I mean my commit

Switch to MySQLi/PDO

MySQL functions should not be used at all, please consider switching to using MySQLi or PDO.

MySQLi is probably best with this class. Will do this, if I get chance.

Is it possible to use keys for both $data and $dataType?

As SecureData is currently written, the function loops to the $key of $data, but references $dataType through an $i variable that is being incremented separately.

Personally I prefer the approach where $dataType contains a list of $data variables, like in this example:

$data = [
    'user' => 'myUserName',
    'password' => 'password',
    'email' => '[email protected]'
];
$dataType = [
    'user' => 'str',
    'password' => 'str',
    'email' => 'email'
];

that way, we can simply loop through $data, use

$data[$key] = $this->CleanData($data[$key], $types[$key]);

Return true in ExecuteSQL could be a confusing point

if($this->records > 0){
$this->ArrayResults();
return $this->arrayedResult;
}else{
return true;
}

When we use ExecuteSQL, commonly here we can't use :

$ret = $db->ExecuteSQL (....);
if (empty($ret)) {
}

coz it's always "TRUE", so you don't know it's empty.

Trailing Comma On Insert Method

My Insert was failing and after looking at the query I was still getting a trailing comma at the end of the generated query. I changed line 160 to $query = substr($query, 0, -2); and it fixed the problem.

Thanks for the great script.

mysql deprecated in php 5.5.x

Hey,

first. thanks for your great work.

second. Because mysql is deprecated in php 5.5.x, I created a class by using mysqli. My class uses yours as base, but because it extends mysqli and s.o. I did not a pull request. Hope it helps anyway.

greetz,
Kanasaru

Nonexistent table creates error

Was trying to create a check to see if a table exists, if it doesn't, then create it.

I noticed that if I try to use it on a nonexistent table, it errors on line 247 or 254 depending on if I use ArrayResult or ArrayResults respectively. Not sure if that's intended or not. I was doing a SELECT, I switched to using SHOW TABLE and that works fine

Return error

Started using your class and it works great except when I had a typo in my SQL and was wondering why nothing was being inserted into my DB. A great addition to the script would be to display an error if a query fails. Keep up the good work.

Add composer

Add composer support so that people using it for package management can also use this class.

Stops working

Hello,

I'm using this wonderfull class in a IRC logbot made in PHP ofcourse ;) with SmartIRC.... But after 115-125 queries it stops working, well, i don't get the usual 1 as return, no error's or such....

As soon as i click on empty truncate function in PHPmyAdmin, restart the bot it works like a charm again.... Is this a bug in the script it self, am i doing something wrong or is it something with the Db?

Code to add something:

function logtext(&$irc, &$data){

            $oMySQL = new MySQL('phpircbot', 'USER', 'PASSWORD', 'HOST');

            $message    = $data->message;
            $channel    = $data->channel;
            $nick       = $data->nick;
            $ident      = $data->ident;
            $host       = $data->host;
            $from       = $data->from;
            $type       = $data->type;
            $date       = date( 'j-n-Y' );
            $time       = date( 'G:i:s' );


            $newLog = array('nick' => $nick,  
              'ident' => $ident,  
              'host' => $host,  
              'type' => $type,  
              'from' => $from,  
              'channel' => $channel,  
              'message' => $message, 
              'time' => $time  
               );

            print_r($newLog);

            $oMySQL->Insert('irclog', $newLog);

            echo $lastError;

        }

when something needs to be logged the function will start, first it creates a new connection, get's all the data then creates the array, prints the array into the console (debug) and sends it into the class to de DB.....

Or should i just start once the new mysql connection as soon as the bot's starts?

Thanks in advance,

//sem

EDIT:
Truncate whole table while bot is running also fixes the problem, so i guess it's a DB problem,.. But still the question tho ;)

Single/Multiple Arrayed Result

It should be nice cosiderate only one way to show results because if your are using this library then you need "two" ways to process data of a "single" or a "multiple" arrayed result. I just commented your code to avoid this.

function ArrayResults()
{

    //if ($this->records == 1) {
    //    return $this->ArrayResult();
    //}

    $this->arrayedResult = array();
    while ($data = mysql_fetch_assoc($this->result)) {
        $this->arrayedResult[] = $data;
    }
    return $this->arrayedResult;
}

Thanks

Update datatypes wheretypes

Hi,
How use datatypes and wheretypes with the update function ?

update($table, $set, $where, $exclude = '', $datatypes, $wheretypes)

$table is a value;
$set is an array
$where is an array

but i don't know how to use/declare datatypes and wheretypes.

Thanks

Select two tables using select query

can i use this method ?
" $where['a.user_id'] = $user_id;
$where['a.oder_id'] = $oder_id;
$where['a.user_id'] = 'b.user_id';
$from = TB_ORDER.'.a, '.TB_USERS.' .b';
$details = $this->Select($from, $where); "

thanks for your code

Return errors from database queries

I really liked this class to use mysql with PDO, but I really need it to return the errors generated by SQL queries.
Before that I used with the php mysqli extension procedurally, but I think there are many unnecessary lines to make prepared statements and I did not want to make my applications vulnerable. This class has already helped me a lot in this, now only need to return the errors of mysql queries.
Thank you!

Please add connect port

38c38
< 

---
>       var $port;      // MySQL Port or path to local UNIX socket 
42d41
< 
47c46
<       function MySQL($database, $username, $password, $hostname='localhost'){

---
>       function MySQL($database, $username, $password, $hostname='localhost', $port = 3306){
52c51
< 

---
>               $this->port     = $port;
68c67
<                       $this->databaseLink = mysql_pconnect($this->hostname, $this->username, $this->password);

---
>                       $this->databaseLink = mysql_pconnect("{$this->hostname}:{$this->port}", $this->username, $this->password);
70c69
<                       $this->databaseLink = mysql_connect($this->hostname, $this->username, $this->password);

---
>                       $this->databaseLink = mysql_connect("{$this->hostname}:{$this->port}", $this->username, $this->password);

wrong use of settype()

in the current commit the settype() function was misleadingly used in the CleanData() function. The result of settype() is not the manipulated data but a boolean result code. This results in empty inserts in many cases.

How to use ArrayResults()?

I believe ArrayResults() will help me maintain the format in outputs i.e. if I select one row or multiple they should both come in an array. How can I use this function ?

New Function and problem with existing function

When it comes to website making, one important aspect is efficiency, and although this class is very simple (which I like), it's not very efficient. Manipulating data in large tables is very slow, and if what you're trying to do (select or delete mostly) can't be done, your current functions are wasteful. Mathematical functions however, are extremely fast because they don't retrieve the actual data. The one in particular that would make this class efficient is using COUNT to make sure data exists before trying to retrieve/delete it. A separate Count function could be useful, or simply add that into the existing functions.

And as for the problem in one of your functions, while browsing the code, I found this in your Select function:
$query = substr($query, 0, -5);
It works perfectly fine, if you leave $operand at it's default. But trying to use OR would have undesired results. It needs to be changed to:
$query = substr($query, 0, ( strlen( $operand ) + 2 ) * -1 );

Edit: As another thought, retrieving all columns is also somewhat inefficient, and the class doesn't have an option for choosing the columns retrieved.

query 'SET NAMES utf8' error: mysql_num_rows() expects parameter 1 to be resource

Hello, when I run the following query $db->ExecuteSQL('SET NAMES utf8'); I get the following error:

 # Line 121
 mysql_num_rows() expects parameter 1 to be resource, boolean given

I fixed with:

 @@ -118,8 +118,13 @@ class MySQL {
      function ExecuteSQL($query){
          $this->lastQuery     = $query;
          if($this->result     = mysql_query($query, $this->databaseLink)){
 -            $this->records   = @mysql_num_rows($this->result);
 -            $this->affected  = @mysql_affected_rows($this->databaseLink);
 +            if (gettype($this->result) === 'resource') {
 +                $this->records   = @mysql_num_rows($this->result);
 +                $this->affected  = @mysql_affected_rows($this->databaseLink);
 +            } else {
 +                $this->records  = 0;
 +                $this->affected = 0;
 +            }

If there is another way to run this query, please tell me

how to get the last id record ?

Hello, well u calss is very very cool !

but how i get the last record using mysql_insert_id() ?,
//return the last id record
function getLastId(){

    return  mysql_insert_id();

}

i have added a function to do it, but maybe u can do it without my function ?

thans to you

method add_table_prefix not found

Thanks for your class. I have used it today but when I use the method exist_table, I got the error at line 43 class.DBDPO.php. That is the method add_table_prefix does not exists.

Thanks!

Dat

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.