GithubHelp home page GithubHelp logo

ezsql / ezsql Goto Github PK

View Code? Open in Web Editor NEW
865.0 102.0 294.0 1.72 MB

PHP class to make interacting with a database ridiculusly easy

Home Page: http://ezsql.github.io/ezsql

License: GNU Lesser General Public License v3.0

PHP 100.00%
dbal php mysqli pgsql sqlite3 sqlserver pdo ezsql shortcut mysql

ezsql's Introduction

ezsql

Windows Linux macOS codecov Codacy Badge Maintainability Total Downloads

A class to make it very easy to deal with database connections. An universal interchangeable CRUD system.

This is Version 5 which will break users of version 4.

Mainly by:

  • The use of namespace in the global functions ezFunctions.php file. Usage of the global functions will require the user to begin a .php file something like:

    use function ezsql\functions\where;
    // Or
    use function ezsql\functions\{
        getInstance,
        selecting,
        inserting,
    };
  • Class properties that was accessible by magic methods get/set, now PSR 1 camelCase.

  • Renamed select of ez_mysqli to dbSelect.

  • Renamed class method and behavior of selecting to select.

  • selecting, and new inserting methods, can be called without table name, only the other necessary parameters:

    • The table name with prefix, can be preset/stored with methods tableSetup(name, prefix), or setTable(name), setPrefix(append), if called without presetting, false is returned.
    • This feature will be added to all database CRUD access methods , each method name will have an ing ending added.
  • Removed global functions where table name passed in, use functions using preset table names ending with ing.

  • renamed cleanInput to clean_string

  • renamed createCertificate to create_certificate

  • added global get_results to return result sets in different formats

Version 4 has many modern programming practices in which will break users of version 3.

Version 3 broke version 2.1.7 in one major way, it required PHP 5.6. Which drop mysql extension support, other than that, nothing as far using the library was changed, only additional features.

This library has an Database class, an combination of the Factory pattern with an Dependency Injection container hosting. This library now is following many OOP principles, one in which, the methods properties public access has been removed. This library also following PSR-2, PSR-4, PSR-11 conventions, and mostly PSR-1, that's still an work in progress.

  • More Todo...

For an full overview see documentation Wiki, which is not completely finish.

Installation

composer require ezsql/ezsql

Usage

require 'vendor/autoload.php';

// **** is one of mysqli, pgsql, sqlsrv, sqlite3, or Pdo.
use ezsql\Database;

$db = Database::initialize('****', [$dsn_path_user, $password, $database, $other_settings], $optional_tag);

// Is same as:
use ezsql\Config;
use ezsql\Database\ez_****;

$settings = new Config('****', [$dsn_path_user, $password, $database, $other_settings]);

$db = new ez_****($settings);

This library will assume the developer is using some sort of IDE with intellisense enabled. The comments/doc-block area will hold any missing documentations. For additional examples see phpunit tests, The tests are fully functional integration tests, meaning the are live database tests, no mocks.

The following has been added since version 2.1.7.

General Methods

to_string($arrays, $separation = ',');
clean($string);
create_cache(string $path = null);
secureSetup(string $key = 'certificate.key',
    string $cert = 'certificate.crt',
    string $ca = 'cacert.pem',
    string $path = '.'._DS
);
secureReset();
create_certificate(string $privatekeyFile = certificate.key,
    string $certificateFile = certificate.crt,
    string $signingFile = certificate.csr,
    string $ssl_path = null, array $details = [commonName => localhost]
);

Shortcut Table Methods

create(string $table = null, ...$schemas);// $schemas requires... column()
column(string $column = null, string $type = null, ...$args);
primary(string $primaryName, ...$primaryKeys);
index(string $indexName, ...$indexKeys);
drop(string $table);

Example

// Creates an database table
create('profile',
    // and with database column name, datatype
    // data types are global CONSTANTS
    // SEQUENCE|AUTO is placeholder tag, to be replaced with the proper SQL drivers auto number sequencer word.
    column('id', INTR, 11, AUTO, PRIMARY), // mysqli
    column('name', VARCHAR, 50, notNULL),
    column('email', CHAR, 25, NULLS),
    column('phone', TINYINT)
);

innerJoin(string $leftTable = null, string $rightTable = null,
    string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);

leftJoin(string $leftTable = null, string $rightTable = null,
    string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);

rightJoin(string $leftTable = null, string $rightTable = null,
    string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);

fullJoin(string $leftTable = null, string $rightTable = null,
    string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);

prepareOn(); // When activated will use prepare statements for all shortcut SQL Methods calls.
prepareOff(); // When off shortcut SQL Methods calls will use vendors escape routine instead. This is the default behavior.

Shortcut SQL Methods

  • having(...$having);
  • groupBy($groupBy);
  • union(string $table = null, $columnFields = '*', ...$conditions);
  • unionAll(string $table = null, $columnFields = '*', ...$conditions);
  • orderBy($orderBy, $order);
  • limit($numberOf, $offset = null)
  • where( ...$whereConditions);
  • select(string $table = null, $columnFields = '*', ...$conditions);
  • create_select(string $newTable, $fromColumns, $oldTable = null, ...$conditions);
  • select_into(string $newTable, $fromColumns, $oldTable = null, ...$conditions);
  • update(string $table = null, $keyAndValue, ...$whereConditions);
  • delete(string $table = null, ...$whereConditions);
  • replace(string $table = null, $keyAndValue);
  • insert(string $table = null, $keyAndValue);
  • create(string $table = null, ...$schemas);
  • drop(string $table = null);
  • alter(string $table = null, ...$alteringSchema);
  • insert_select(string $toTable = null, $toColumns = '*', $fromTable = null, $fromColumns = '*', ...$conditions);
// The variadic ...$whereConditions, and ...$conditions parameters,
//  represent the following global functions.
// They are comparison expressions returning an array with the given arguments,
//  the last arguments of _AND, _OR, _NOT, _andNOT will combine expressions
eq('column', $value, _AND), // combine next expression
neq('column', $value, _OR), // will combine next expression again
ne('column', $value), // the default is _AND so will combine next expression
lt('column', $value)
lte('column', $value)
gt('column', $value)
gte('column', $value)
isNull('column')
isNotNull('column')
like('column', '_%?')
notLike('column', '_%?')
in('column', ...$value)
notIn('column', ...$value)
between('column', $value, $value2)
notBetween('column', $value, $value2)
// The above should be used within the where( ...$whereConditions) clause
// $value will protected by either using escape or prepare statement
// To allow simple grouping of basic $whereConditions,
// wrap the following around a group of the above comparison
// expressions within the where( ...$whereConditions) clause
grouping( eq(key, value, combiner ), eq(key, value, combiner ) )
// The above will wrap beginning and end grouping in a where statement
// where required to break down your where clause.
// Note: The usage of this method will require the user/developer to check
// if `query_string` or `param_array` is valid.
//
// This is really an `private` internal method for other shortcut methods,
// it's made public for `class development` usage only.
//
//
// Supply the the whole `query` string, and placing '?' within, with the same number of arguments in an array.
// It will then determine arguments type, execute, and return results.
query_prepared(string $query_string, array $param_array);
// You will need to call this method to get last successful query result.
// It wll return an object array.
queryResult();

Example for using prepare statements indirectly, with above shortcut SQL methods

// To get all shortcut SQL methods calls to use prepare statements
$db->prepareOn(); // This needs to be called at least once at instance creation

$values = [];
$values['name'] = $user;
$values['email'] = $address;
$values['phone'] = $number;
$db->insert('profile', $values);
$db->insert('profile', ['name' => 'john john', 'email' => 'john@email', 'phone' => 123456]);

// returns result set given the table name, column fields, and ...conditions
$result = $db->select('profile', 'phone', eq('email', $email), between('id', 1, $values));

foreach ($result as $row) {
    echo $row->phone;
}

$result = $db->select('profile', 'name, email',
    // Conditionals can also be called, stacked with other functions like:
    //  innerJoin(), leftJoin(), rightJoin(), fullJoin()
    //      as (leftTable, rightTable, leftColumn, rightColumn, tableAs, equal condition),
    //  where( eq( columns, values, _AND ), like( columns, _d ) ),
    //  groupBy( columns ),
    //  having( between( columns, values1, values2 ) ),
    //  orderBy( columns, desc ),
    //  limit( numberOfRecords, offset ),
    //  union(table, columnFields, conditions),
    //  unionAll(table, columnFields, conditions)
    $db->where( eq('phone', $number, _OR), neq('id', 5) ),
    //  another way: where( array(key, operator, value, combine, combineShifted) );
    //  or as strings double spaced: where( "key  operator  value  combine  combineShifted" );
    $db->orderBy('name'),
    $db->limit(1)
);

foreach ($result as $row) {
    echo $row->name.' '.$row->email;
}

// To get results in `JSON` format
$json = get_results(JSON, $db);

Example for using prepare statements directly, no shortcut SQL methods used

$db->query_prepared('INSERT INTO profile( name, email, phone) VALUES( ?, ?, ? );', [$user, $address, $number]);

$db->query_prepared('SELECT name, email FROM profile WHERE phone = ? OR id != ?', [$number, 5]);
$result = $db->queryResult(); // the last query that has results are stored in `lastResult` protected property
// Or for results in other formats use the global function, will use global database instance if no `$db` supplied
$result = get_results(/* OBJECT|ARRAY_A|ARRAY_N|JSON */, $db); // Defaults to `OBJECT`

foreach ($result as $row) {
    echo $row->name.' '.$row->email;
}

Most of shortcut methods have counter global functions available. They can only be access by beginning your .php file like:

use function ezsql\functions\functionBelow;
// Or as here, a complete list.
use function ezsql\functions\{
    database,
    mysqlInstance,
    pgsqlInstance,
    mssqlInstance,
    sqliteInstance,
    pdoInstance,
    tagInstance,
    setInstance,
    getInstance,
    clearInstance,
    get_vendor,
///
    to_string,
    clean_string,
    is_traversal,
    sanitize_path,
    create_certificate,
///
    column,
    primary,
    foreign,
    unique,
    index,
    addColumn,
    dropColumn,
    changingColumn,
///
    eq,
    neq,
    ne,
    lt,
    lte,
    gt,
    gte,
    isNull,
    isNotNull,
    like,
    in,
    notLike,
    notIn,
    between,
    notBetween,
///
    where,
    grouping,
    groupBy,
    having,
    orderBy,
    limit,
    innerJoin,
    leftJoin,
    rightJoin,
    fullJoin,
    union,
    unionAll,
///
    creating,
    deleting,
    dropping,
    replacing,
    selecting,
    inserting,
    altering,
    get_results,
    table_setup,
    set_table,
    set_prefix,
    select_into,
    insert_select,
    create_select,
};

For the functions usage/docs see ezFunctions.php.

For Authors and Contributors

Contributing

Contributions are encouraged and welcome; I am always happy to get feedback or pull requests on Github :) Create Github Issues for bugs and new features and comment on the ones you are interested in.

License

ezsql is open-sourced software licensed originally under (LGPL-3.0), and the addon parts under (MIT).

ezsql's People

Contributors

abelcallejo avatar crimsonfalconer avatar dpdesignz avatar fawaf avatar hubaishan avatar if3lc avatar johnrdorazio avatar jspringe avatar jv2222 avatar lsproc avatar lucanos avatar madvik avatar mavroudis avatar merkdev avatar mikesalmonuk avatar ozh avatar ricardopadilha avatar rusdyahmad avatar rythie avatar salehobaid avatar scottmci avatar sugavanas avatar szepeviktor avatar thetechstech avatar vetrijar avatar winkm89 avatar wninaus avatar xymanek avatar yohancreemers avatar yuks 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  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

ezsql's Issues

mysql_* functions

Looking at the code, you may wish to consider using the mysqli_* functions in future releases. On the PHP functions website they're strongly discouraging people from using mysql_* functions and to instead use the mysqli_* equivalent.

Select count(*) broken in sqlsrv

For some reason, I can't do $db->get_var("Select count(*) from table_name where id=1 ") (Replacing, of course, table_name with the name of my table, and id with the id.

Note: it's not because of bad SQL, as I ran the SQL in Microsoft SQL Server Management Studio, and it worked just fine.

EZ SQL outputs no errors (even to the php log), but returns null. Trying $db->debug() outputs that it got my query, but under Row it says dt not defined. I could not find reference to this error anywhere.

Note 2: This same query works fine with the mySqli class (and mySql database).

mysqli - query function

Hello,

It seems that the ine ez_sql_mysqli.php module, in the the query function has a problem.

If the num_queries var is more than 500, the disconnect() function is called, then the quick_connect().

The problem is that the disconnect() function does only a close() on the database, with no killing of the thread.

In fact, the new connection creates a new thread, and so on... till the MySQL refuses the connection and hangs with a timeout.

Is there any solution to that (of cours, if we delete the code keeping alive, it works) ?

Thanks by advance.

Galawa

ezsql_pdo bug: once a query fails, following queries fail

There's a bug in the PDO class: once you raise an error (eg try to insert data into a table that doesn't exist) all subsequent queries fail

Example:

// init the PDO connection, then :

// valid query :
var_dump( $db->query( "SHOW TABLES" ) );
// Works, shows correct result

// invalid query :
var_dump( $db->query( "INSERT INTO omgblah VALUES (value1, value2, value3)" ) );
// Doesn't work, throws a warning and returns false as expected

// valid query :
var_dump( $db->query( "SHOW TABLES" ) );
// Unexpectedly still throws warning + returns false

The problem sits in ez_sql_pdo.php, function query(). Once an error has been catched, it prevents subsequent queries from completing.

I'm not sure how to fix this, I'm lost between PDO's exec vs execute vs query ...

Invalid var in ez_sql_postgresql.php

diff --git a/postgresql/ez_sql_postgresql.php b/postgresql/ez_sql_postgresql.php
index 36aae74..8143b4d 100755
--- a/postgresql/ez_sql_postgresql.php
+++ b/postgresql/ez_sql_postgresql.php
@@ -13,7 +13,7 @@
* ezSQL error strings - PostgreSQL
*/

  •   global ezsql_postgresql_str;
    
  •   global $ezsql_postgresql_str;
    
    $ezsql_postgresql_str = array
    (
    

    @@ -287,4 +287,4 @@
    }
    }

  •   }
    

    \ No newline at end of file

  •   }
    

ez_sql_mysqli.php

Getting no results on selects with this version of mysqli. Older versions worked ok.

ezSQL library and mysql reserved words

Sorry, i've not find out the way to solve correctly a query with ezSQL if the query contain a Reserved MySQL Word.
So, as example:
INSERT INTO content (id, asset_id, title, alias, fulltext) .....
as fulltext is a reserved mysql word, ezSQL return trigger error.
I've try to modify the ezsql core file, but without success until now.

ezSQL abnormal behaviour

I am using ezSQL for database queries and connection and sometimes it gives data and sometimes it return no results.

Here is the debug code

Query [3] -- [SELECT * FROM table WHERE `id`=4]
Query Result..

No Results

Database table have records and it return records if i run file after few minutes.

sqlsrv $this->count broken

PHP error:
PHP Fatal error: Call to undefined method ezSQL_sqlsrv::count() in C:\inetpub\wwwroot\bx\UI\includes\ez_sql_sqlsrv.php on line 182

Reference to:
$this->count(true, true); (line 182 of ez_sql_sqlsrv.php)

php -v outputs:

PHP 5.6.15 (cli) (built: Oct 29 2015 12:40:34) Copyright (c) 1997-2015 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

Request - Composer Installation/Invocation Instructions

Hey everyone,

For some of you, it may be exceedingly simple, but for someone unfamiliar with it as myself, I am trying to learn to use Composer, and to continue to use the ezSQL class in my projects.

I have found the ezSQL Package at Packagist (https://packagist.org/packages/jv2222/ezsql) and have installed it (I think), but it would be great is the ReadMe or Wiki could be extended to detail how to do this, and how ezSQL should be invoked in a Composer-based build.

Just a suggestion - not a bug.

Luke

Postgre warning

Hi,

To prevent PHP warning with EzSQL Postgre, I had to add this on line #240 :

$this->col_info[$i] = new stdclass();

Hope that helps,
Nicolas

Cache clashing and ballooning?

We've been using ezSQL (mysql) on a app for several years now and never had any problems at until recently. We found that over the past few months, every so often the server would get wiped out by a memory issue - the server has a significant amount of memory, so it seemed odd.

After investigation, we found that a cache file would be responsible. Most cache files are significantly smaller than < 0.5MB, but every so often, one cache file balloons over an arbitary period of time. We don't know what triggers it, but it grows, and grows and grows (the speed depends on how big the query result is), until it gets called, and the massive (sometimes 150MB+ file) gets called by the application, and then of course it stalls the whole apache server. The cache file is not the same file name, query or hash - it appears to happen at complete random.

Deleting the huge file restores the server to working state immediately, and the file re-caches immediately, perfectly.

The ballooned file contents are curious. They do contain the correct serialised results, but then these contents are repeated, over and over and over. It's like the file is being written to, but never sealed, then written to again with identical content.

It only appears to affect one cache file at a time. There are often thousands of cache files in the folder.

A friend who has looked at the code thinks that it could be down to two processes writing to the file at exactly the same time. He says the chances of this happening (because the file isn't locked) are raised if the queries take a particularly long time to execute. Even more curiously, the file content in some cases appears to repeat exactly 1024 times (although I can't confirm how many times that has happened)

I cannot find any other mention of this issue online, but at the moment we think this 'clash' idea could be real, and our very temporary solution is deleting any cache file over 1Mb at a set interval using a cron to prevent escalation.

Justin, or anyone else who might know, might you be able to confirm this is likely to be our issue, or do you think can we rule it out?

Andy.

Specify a custom port is not always possible across classes

Hi

Currently there is no consistent way across classes to specify a port.

  • cubrid and postgresql constructor functions accept a port number as argument
  • other classes don't explicitly accept a port argument. In these, some DB engines (mysql, mssql) accept a "hostname:port" notation (eg "localhost:3306") but some others (mysqli, pdo, sqlsrv) need specific stuff
  • depending on the DB engine, you cannot simply use ezSQL at the moment if you use a non standard port

I'm willing to fix this inconsistency and to submit a pull request but I'm seeking for approval before I start coding :)

My idea would be to accept the "hostname:port" notation in all classes, to preserve the number and order of arguments in all constructors as they are now (and not to break any script that would update after you commit the PR)

Any thoughts?

Error suppression discussion

I had previously added this to the discussion for #27, but now that has been merged in, the discussion is lost, so think it should now have it's own issue. Original comment:

This also brings up the issue of error suppressing. I'm not a fan of it at all, but in some cases, ezSQL does some checking of it's own for errors and then manually uses trigger_error to throw one up. An example being:

if ( $str = @$this->dbh->error )
{
    $is_insert = true;
    $this->register_error($str);
    $this->show_errors ? trigger_error($str,E_USER_WARNING) : null;
    return false;
}

However, this issue was difficult to track down because of:

while ( $row = @$this->result->fetch_object() )

There is no error checking that ezSQL does. The error should have been saying trying to call fetch_object on a non-object (or something similar).

I don't think this use of error suppressing is justified. It makes things really difficult to debug. Especially when it's a bug with ezSQL and not anything else.

There's concern that if we remove error suppression from this example line, that lots of people will then get notice warnings.

However, if an error (not a notice) is triggered here, there is a genuine issue with the way someone is using ezSQL, and they need to be made aware of that. Other than painstakingly debugging their code, and then ezSQL.

Postgres: INSERT queries into tables that do not have an autoincrement column do not work

Scenario:
An association table called "userinventory" that has two columns, both are foreign keys: userId and ingredientId. There is no autoincrement column.

Query: INSERT INTO userinventory (userid, ingredientid) VALUES (179, 3), (179, 5);

This query does not work in ezSql because ezSql attempts to get the insertID - and there is not one. The error message is:

Warning: pg_query(): Query failed: ERROR: lastval is not yet defined in this session in ..../ez_sql/postgresql/ez_sql_postgresql.php on line 220

Warning: pg_fetch_row() expects parameter 1 to be resource, boolean given in ..../ez_sql/postgresql/ez_sql_postgresql.php on line 221

Replace/Insert a row into a table shortcuts

Just a suggestion to make two shortcut functions named replace and insert as used in WordPress:

function replace( $table, $data, $format = null ) {
        if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
            return false;
        }

        $data = $this->process_fields( $table, $data, $format );
        if ( false === $data ) {
            return false;
        }

        $formats = $values = array();
        foreach ( $data as $value ) {
            $formats[] = $value['format'];
            $values[]  = $value['value'];
        }

        $fields  = '`' . implode( '`, `', array_keys( $data ) ) . '`';
        $formats = implode( ', ', $formats );

        $sql = "$type INTO `$table` ($fields) VALUES ($formats)";

        $this->check_current_query = false;
        return $this->query( $this->prepare( $sql, $values ) );
}

The usage would be;

$replace_review_snapshot = $this->db->replace($product_reviews_table, array(
                'id' => 1,
                'my_review' => $data['info']['something'],
                'my_name' => mysql_real_escape_string($data['info']['my_name']) ,
                'my_stars' => $data['info']['couting'],
            ) , array(
                '%d',
                '%s',
                '%s',
                '%d'
            ));

grant queries are failing silently

I just spent several hours debugging this.
turns out there is logic in ezsql that detects if a query is a select (in all drivers), and in that case it fetches the rows.
preg_match("/^(insert|delete|update|start|replace|truncate|drop|create|alter|begin|commit|rollback|set|lock|unlock|call)/i",$query) )

if the query is unrecognized (like grant queries) it will assume it's a select and will try to read the resulting data.
since ezsql really likes to hide the errors with @ for every operation, this results in php exiting silently.

the solution is as simple as adding grant to the regexp above, but I think the logic should be reversed:
if something is a select, fetch the data (IE: it has select in the query start).

SQL Injection Protection

Has their been any work done to protect from SQL injection in ezSQL? I've seen safeSQL? (I think that is what it is.) Is that all that is out there? And, if so, why isn't this built directly into ezSQL?

New error with ez_sql_postgresql.php line 147

A typo error was introduced in 2.17 or commit (6cca79) with proposed resolution below:

-           return return "ordinal_position, column_name, data_type, column_default, is_nullable, character_maximum_length, numeric_precision FROM information_schema.columns WHERE table_name = '$tbl_name' AND table_schema='$this->dbname' ORDER BY ordinal_position";
+           return "ordinal_position, column_name, data_type, column_default, is_nullable, character_maximum_length, numeric_precision FROM information_schema.columns WHERE table_name = '$tbl_name' AND table_schema='$this->dbname' ORDER BY ordinal_position";

patch

"prepare" need to add in the ez_sql_mysql.php

Hi,

I like the ezsql and will use in my all projects from now.. but i have one request... please add a prepare function which is also used in the wordpress.... for queires.. i am also pasting this function here..

//USAGE
    $sTemp  = "INSERT INTO best_cms (";
    $sTemp .= "pagename,pagedetail,status ";//4
    $sTemp .= ") VALUES (";
    $sTemp .= " %s, %s, %s";
    $sTemp .= ")";
  $sQuery = $wpdb->prepare($sTemp,'temp', '<p>temp\'</p>', 1);
  $aResult = $wpdb->query($sQuery);

//FUNCTION NEED TO ADD IN ez_sql_mysql.php

    /**
     * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
     *
     * The following directives can be used in the query format string:
     *   %d (integer)
     *   %f (float)
     *   %s (string)
     *   %% (literal percentage sign - no argument needed)
     *
     * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
     * Literals (%) as parts of the query must be properly written as %%.
     *
     * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
     * Does not support sign, padding, alignment, width or precision specifiers.
     * Does not support argument numbering/swapping.
     *
     * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
     *
     * Both %d and %s should be left unquoted in the query string.
     *
     * <code>
     * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
     * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
     * </code>
     *
     * @param string $query Query statement with sprintf()-like placeholders
     * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
     *  {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
     *  being called like {@link http://php.net/sprintf sprintf()}.
     * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
     *  {@link http://php.net/sprintf sprintf()}.
     * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
     *  if there was something to prepare
     */
function prepare( $query, $args ) {
        if ( is_null( $query ) )
            return;

        $args = func_get_args();
        array_shift( $args );
        // If args were passed as an array (as in vsprintf), move them up
        if ( isset( $args[0] ) && is_array($args[0]) )
            $args = $args[0];
        $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
        $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
        $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
        $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
        array_walk( $args, array( $this, 'escape_by_ref' ) );
        return @vsprintf( $query, $args );
    }

    /**
     * Escapes content by reference for insertion into the database, for security
     *
     * @return void
     */
    function escape_by_ref( &$string ) {
        if ( ! is_float( $string ) )
            $string = $this->escape( $string );
    }   

Declare $rows_affected

Need to declare $rows_affected in ez_sql_mysql.php. Otherwise, PHP will generate an Undefined property notice when trying to read $db->rows_affected.

All-in-one file packet version

Hi!

I think should be more usable a distribution targetted for specific driver (like MySQL) encapsuled into one file:

ezsql.mysql.pack.php

that contain "core" and "mysql"

is the best for me...

What happened to ez_results.php

Hello, I am upgrading an app that uses EZSQL v1.26. I was using ez_results.php v1.16, which I thought was part of the EZSQL package. I do not see an ez_results class in the new code. Was this dropped? If yes, any particular concerns?

Deprecated php functions on php 7.0

Deprecated: Function eregi_replace() is deprecated in ez_sql_mssql.class.php on line 356
Deprecated: Function eregi() is deprecated in ez_sql_mssql.class.php on line 364

The class should be re-written for php 7.0 full compatibility

After 500 queries script reconnects after each query

The test $this->num_queries >= 500 on line 207 of mysqli/ez_sql_mysqli.php will be true for each query as soon as the the 500 limit has been passed.

Suggestion: the test $this->num_queries % 500 == 499 will be true each 500st query.

ezSQL for MS SQL driver

Created sqlsrv tree off of root to support the microsoft support sql server driver (tested on v3.0) ...
Will append in my next post if someone wants to include it with the distribution or improve upon it.

Support Windows Authentication if you do not put data in the UN/PW fields.

ez_sql_mysql escape() function spoils strings with the slashes

I'm trying to INSERT json-encoded array in the TEXT field with ez_sql_mysql wrapper. I'm using escape() function for every string variable before it passes to the query. My string contains Unicode characters, so my array encoded like this: ["","'bar'",""baz"","&blong&","\u00e9"].

Now I found that all my slashes is missing.

I have searched through the code and found root cause of problems: wrong call of stripslahes() function at 177 line of the ez_sql_mysql.php:
return mysql_real_escape_string(stripslahes($str));

I have deleted stripslashes() call and now all works fine!

Support for PDO MySQL

-- edit -- I'm out of my mind, that didn't make sense. Apologies for opening a useless issue :)

Disconnection on middle of a mysql transaction because num_queries >= 500

Hi guys,

Our company was needing to run a migration system that had a lot of queries (mostly inserts and selects). Everything was wrapped in a large transaction.

It took a lot to be able to fix the problem and, in the end, we discovered a bug in ezsql (mysq conector).

The system automatically disconnects and reconnects if the number of queries is greater than 500. This is good because it makes the system stable but it forces an implicit ROLLBACK if a transaction is in progress.
Screenshot on 3 22 2013 at 2 40 53 AM

Therefore, you should create a check to disable this disconnection if a transaction is still running.

Thank you. Keep up the good work. :)

Sincerely,
Renan Gomes
Project Manger at GeoRanker.com
http://www.georanker.com
http://apidocs.georanker.com

escape() function

Hi, I'm new in github and I'm not sure if I can ask this question here..

It's about the $db->escape() function; Where should I use it? Always that I get data from a user form (via GET or POST) ???

It's really secure to use this function to avoid all Sql Injection attempts ?

Thanks!
Raúl.

is_insert issue

Hi

ive been using your class now for a while and had no issues at all, this morning however ive stumbled across a slight issue that i think might be a bug. Its to do with multiple inserts not working correctly.

I believe the issue might be around this area of the query function in the mysql class. If there is a mysql error you return false and assign the errors which is fine but prior to this you set the $is_insert variable to true which has no real effect on anything as far as i can see. now if there is no error you set the $is_insert to false.

    // Perform the query via std mysql_query function..
            $this->result = @mysql_query($query,$this->dbh);

            // If there is an error then take note of it..
            if ( $str = @mysql_error($this->dbh) )
            {
                $is_insert = true;
                $this->register_error($str);
                $this->show_errors ? trigger_error($str,E_USER_WARNING) : null;
                return false;
            }

            // Query was an insert, delete, update, replace
            $is_insert = false;
            if ( preg_match("/^(insert|delete|update|replace|truncate|drop|create|alter)\s+/i",$query) )
            {
                $this->rows_affected = @mysql_affected_rows($this->dbh);

                // Take note of the insert_id
                if ( preg_match("/^(insert|replace)\s+/i",$query) )
                {
                    $this->insert_id = @mysql_insert_id($this->dbh);
                }

                // Return number fo rows affected
                $return_val = $this->rows_affected;
            }

when you then perform the preg_match on the query and go into that section of the code you run a check to see if this is a insert or a replace it its a insert you set the insert_id but you dont change the value of the $is_insert variable and this seems to cause a issue basically im running a query that looks like this.

INSERT INTO rmp_service_bookings SET
                        fk_service_type_id = '136',
                        fk_comp_id = '791',
                        booked_by_fk_user_id = '7',
                        datetime_added = NOW(),
                        live = 0

now im actually running the same query 20 times depending on how many bookings of that service there are, then im using the insert_id that should be generated to insert a record into another table the insert looks like this.

INSERT INTO rmp_service_campaigns_bookings SET
                                            fk_campaign_id = '949',
                                            fk_booking_id = '11198',
                                            fk_user_created_id = '7',
                                            created = NOW(),
                                            updated = NOW()

now when i first run this only 2 booking ever appeared in the second table and I wasnt sure why, after i logged out the queries that were being run I could see that it was only ever inserting the one query. Now when i turned off use_disk_cache this seemed to solve the issue. Should insert statements actually be cached like this?

When i looked further down the query function i saw the following

// disk caching of queries $this->store_cache($query,$is_insert);

After looking at the store_cache function i could see that the it uses the $is_insert variable passed to it to check the cache. now when i leave the setup as it was prior to turning off use_disk_cache only 2 bookings where inserted after that none of the others were done. The issue appears to be with the insert_id always coming back as the same thing, now when i disable disk_cache everything works as expected and this insert_id increases correctly and all the items appear in the database as expected.

So the question is should the $is_insert be being set to true, as when i update the query function with the following

    // Take note of the insert_id
                if ( preg_match("/^(insert|replace)\s+/i",$query) )
                {
                                        //check if this is a insert and set to true
                    if ( preg_match("/^(insert)\s+/i",$query))
                        $is_insert = true;
                    $this->insert_id = @mysql_insert_id($this->dbh);
                }

the issue that i have is fixed without having to turn the disk cache off.

thanks

ez_sql_mysqli.php

There has to be a bug in the latest ez_sql_mysqli.php file, when I upgrade to the latest version, some queries return No Results, when there should be results, as soon as I replace it with an older version of ez_sql_mysqli.php, the results are returned as expected.

sqlsrv insert_id returns nothing

Hi, after inserting new row to MsSQL database, $db->insert_id returns nothing.

if ( preg_match("/^(insert|replace)\s+/i",$query) )
{
    $identityresultset = @sqlsrv_query($this->dbh, "select SCOPE_IDENTITY() AS id");

    if ($identityresultset != false )
    {
        $identityrow = @sqlsrv_fetch($identityresultset);

        $this->insert_id = $identityrow[0];
    }
}

$identityresultset returns resource, $identityrow returns bool(true)

Oracle max-length fix

I use ezSQL with Oracle, and I'm not sure if this is an issue with other databases or not. If I perform a query like this -

select count(*) from table where name like 'W%'
I would get :
PHP Notice: Undefined property: stdClass::$max_length in /home/jadu/public_html/a/lib/db/ez_sql_core.php on line 451

I took a look at 451 - and when selecting count(*) there is no "max_length", its actually "size" when this query runs.

I've altered ez_sql_core.php and changed line 451 to this if statement, the the problem went away. There's probably a better way to do this, but I was in a hurry to hack together a fix.

if (!isset($this->col_info[$i]->max_length)) {
echo "{$this->col_info[$i]->type} {$this->col_info[$i]->size}
{$this->col_info[$i]->name}";
} else {
echo "{$this->col_info[$i]->type} {$this->col_info[$i]->max_length}
{$this->col_info[$i]->name}";
}

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.