GithubHelp home page GithubHelp logo

pdo's Introduction

PDO

Latest Stable Version Total Downloads Latest Unstable Version License

Just another PDO database library

Installation

Use Composer

$ composer require faapz/pdo 

Usage

Examples selecting, inserting, updating and deleting data from or into users table.

require_once 'vendor/autoload.php';

$dsn = 'mysql:host=your_db_host;dbname=your_db_name;charset=utf8';
$usr = 'your_db_username';
$pwd = 'your_db_password';

$database = new FaaPz\PDO\Database($dsn, $usr, $pwd);

// SELECT * FROM users WHERE id = ?
$select = $database->select()
                   ->from('users')
                   ->where(new FaaPz\PDO\Clause\Conditional('id', '=', 1234));

if ($insert->execute()) {
    $data = $stmt->fetch();
}

// INSERT INTO users (id , username , password) VALUES (? , ? , ?)
$insert = $database->insert(
                       'id',
                       'username',
                       'password'
                   )
                   ->into('users')
                   ->values(
                       1234,
                       'user',
                       'passwd'
                   );

if ($insert->execute()) {
    $insertId = $database->lastInsertId();
}

// UPDATE users SET pwd = ? WHERE id = ?
$update = $database->update(["pwd" => "your_new_password"])
                   ->table("users")
                   ->where(new FaaPz\PDO\Clause\Conditional("id", "=", 1234));

if (($result = $insert->execute()) !== false) {
    $affectedRows = $result->rowCount();
}

// DELETE FROM users WHERE id = ?
$delete = $database->delete()
                   ->from("users")
                   ->where(new FaaPz\PDO\Clause\Conditional("id", "=", 1234));

if (($result = $delete->execute()) !== false) {
    $affectedRows = $result->rowCount();
}

The sqlsrv extension will fail to connect when using error mode PDO::ERRMODE_EXCEPTION (default). To connect, you will need to explicitly pass array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING) (or PDO::ERRMODE_SILENT) into the constructor, or override the getDefaultOptions() method when using sqlsrv.

Documentation

See DOCUMENTATION

Changelog

See CHANGELOG

License

See LICENSE

pdo's People

Contributors

bmutinda avatar delef avatar faapz avatar ismnoiet avatar kwhat avatar mridah avatar mystael avatar scheras avatar terah avatar tonylevid avatar wfrancois 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

pdo's Issues

Order By clause may not apply to update or delete.

Should order by clause be available in UPDATE or DELETE? I noticed that its currently on the StatementContainer but it will not work on MsSQL for UPDATE and DELETE. Not sure what other sql may expect.

V2 Road Map

V2 Road Map

  • Interfaces for all classes
  • No more private variables and functions, only protected
  • Correct use of getters & setters
  • Support for strings ('one, two'), arrays ([$one, $two]) and ... parameters
  • Nested queries
  • Field aliases AS in SELECT clauses
  • ON DUPLICATE KEY UPDATE (#32)
  • Detect database driver (could be useful for e.g. #29)
  • Required PHP version to 7.2
  • Rename on Packagist
  • Unit Tests

If anyone has any suggestions, let me know! 🙏

setPlaceholders doesn't handle NULL values correctly

I'm attempting to insert a row that has NULL values in the data array coming in, like this:

$pdo->insert([ 'id', 'usr', 'pwd', 'name' ])
    ->into( 'users' )
    ->values([ 1234, 'your_username', 'your_password', NULL ])
    ->execute();

setPlaceholders looks like it passes a sizeof($value) argument to setPlaceholder, but if the value is NULL then this will send in 0 there. This produces a SQL string that throws an error:

INSERT INTO users ( id , usr , pwd , name ) VALUES ( ? , ? ,  , ? )

I feel like the expected behavior is to just add the ? regardless if the value has a size.

Update date and add days

I would like to know how can i update the existing date and add some days to it.
Example. update( ['date' => "DATE_ADD('date' , INTERVAL 2 DAY)" ] ).

Or how can i add a native sentence in the update function like SET date = "DATE_ADD('date' , INTERVAL 2 DAY)".

Thanks in advance

Join on multiple columns

Hi,

I was wondering if it is already possible to join on multiple columns..? If not, I provided an example function to add this to the library.

Is this possible with the current library?

SELECT *
FROM A
INNER JOIN B ON  A.col1 = B.col1
             AND A.col2 = B.col2;

If not, could you implement something like this:

    /**
     * @param string $table
     * @param array  $columns
     * @param string $joinType
     * @param string $operator
     * @param string $chainType
     */
    public function joinOnMultiple($table, array $columns, $operator, $joinType = 'INNER', $chainType = 'AND') {
        $string = ' ' . $joinType . ' JOIN ' . $table . ' ON ' . key($columns[0]) . ' ' . $operator . ' ' . $columns[0];

        unset($columns[0]);

        if (!empty($columns)) {
            foreach ($columns as $first => $second) {
                $string .= ' ' . $chainType . ' ' . $first . ' ' . $operator . ' ' . $second;
            }
        }

        $this->_container[] = $string;
    }

so we can achieve the query by doing:

$statement->joinOnMultiple('B', [
    'A.col1' => 'B.col1',
    'A.col2' => 'B.col2',
], '=');

Thanks in advance!

Setting \PDO::ATTR_ERRMODE doesn't work for SQLSRV

Creating a new Database instance with SQLSRV throws the following:

The given attribute is only supported on the PDOStatement object.

$pdo = new \Slim\PDO\Database($dsn, $username, $password);

If I comment out the following line, the error doesn't get thrown and I can use the database object as intended.

\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,

Remove redundant * when use count()

$selectStatement = new SelectStatement($this->pdo, array('*'));
// or
$selectStatement = $this->pdo->select();

$sel = $selectStatement->from('dede_archives')->count();
echo $sel;

result

SELECT * , COUNT( * ) FROM dede_archives

maybe in front of * can be removed

Overwrite default options

Referenced in #11

It's not possible to overwrite any options set in Database::getDefaultOptions() when passing the $options array into the constructor.

Line 31 should be:

$options = $options + $this->getDefaultOptions();

Update LimitClause doesn't use proper Postgres "OFFSET" syntax

Proper Postgres syntax is LIMIT 10 OFFSET 0
This is after updating to v1.10.0

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42601]: Syntax error: 7 ERROR: LIMIT #,# syntax is not supported LINE 10: ) = $1 LIMIT 0 , 10 ^ HINT: Use separate LIMIT and OFFSET clauses.' in /vendor/slim/pdo/src/PDO/Statement/StatementContainer.php:429 Stack trace: #0 /vendor/slim/pdo/src/PDO/Statement/StatementContainer.php(429): PDOStatement->execute(Array) #1 /vendor/slim/pdo/src/PDO/Statement/SelectStatement.php(411): Slim\PDO\Statement\StatementContainer->execute() #2 /user/file.php(382): Slim\PDO\Statement\SelectStatement->execute() #3 /user/file2.php(76): UserFunction() #4 {main} thrown in /vendor/slim/pdo/src/PDO/Statement/StatementContainer.php on line 429

InsertStatement execute problem

Hi,

$insertStatement = $pdo->insert($fields)->into('accounts')->values($values);
$insertId = $insertStatement->execute();

$insertId is always <= 0 and nothing is inserted.

To fix this I need to do lke this:

$insertId = $insertStatement->execute(false); // now it is OK.

Why you do this?

public function execute($insertId = true){
        if (!$insertId) {
            return parent::execute();
        }

        return $this->dbh->lastInsertId();
}

Thanks.

Error using LIMIT with mysql

I get this error when using LIMIT with mysql DB

Fatal error: Expects parameters as integers in /home/public_html/api/vendor/slim/pdo/src/PDO/Clause/LimitClause.php on line 29

My code is below:
$selectStatement = $pdo->select()
->from('news')
->limit(10);

How to select all the records ?

I want to fetch all the records therefore I've tried :

  • without where()
$selectStatement = $pdo->select()
                               ->from('user')
  • with limit(bigNumber)
$selectStatement = $pdo->select()
                               ->from('user')
                               ->limit(1000000);        

Followed by :

$stmt = $selectStatement->execute();
        $data = $stmt->fetch(); 

        print_r($data);

But i get only the first record in return, would you tell me what i'm missing here ?

Thank you.

Doesn't support DATE/TIME types in WHERE clause

I don't know if this is a problem with PDO or with this library.

I am trying to use this WHERE clause:

->where("date", ">", "CURRENT_DATE - INTERVAL '90 days'")

but I get this exception:

Uncaught exception 'PDOException' with message 'SQLSTATE[0A000]: Feature not supported: 7 ERROR:  date/time value &quot;current&quot; is no longer supported' in .../vendor/slim/pdo/src/PDO/Statement/StatementContainer.php:404

Is it possible to use DATE/TIME variables in PostgreSQL like CURRENT_DATE?

Join not working with where

Hi,

My query is

$resultObj = $this->db->select()->from('shuttles')
->leftJoin('routes', 'routes.id', '=', 'shuttles.route_id')
->leftJoin('schedules', 'schedules.id', '=', 'shuttles.schedule_id')
->where('shuttles.id', '=', '4')
->where('shuttles.status','=','active')->execute();

    $result = $resultObj->fetchAll();

[Uploading whirlpool_mobility_qa3-29 PMtest.txt…](SQL export of tables)

its not returning me data for shuttle id =4.

Join not working with where conditions.
Can you please let me know the solution for the same

Cannot use orderBy in query

I had problem with Order By. It return error "SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order = ? ORDER BY name_en ASC' at line 1"

This is my code
$query = $this->db->select()->from('provinces');
$query->orderBy('name_en');
$result = $query->execute();

How can I Fix It.

Parenthetical grouping in where clause

Is there a way to group like (this = that AND that = this) AND (foo = bar OR foo = baz)

Query try 1:

    $selectStatement = $dbw->select($fields)
        ->from('projects p')
        ->join('int_users_projects iup', 'p.id', '=', 'iup."fkProjectId"')
        ->join('clients c', 'p."fkClientId"', '=', 'c.id')
        ->where('iup."fkUserId"', '=', $authUser->getId(), 'AND')
        ->where('p."fkSuperUserId"', '=', $authUser->getId(), 'OR')
        ->where('p.status', '=', 'active', 'AND')
        ->where('c.status', '=', 'active', 'AND');

Query try 2:

    $selectStatement = $dbw->select($fields)
        ->from('projects p')
        ->join('int_users_projects iup', 'p.id', '=', 'iup."fkProjectId"')
        ->join('clients c', 'p."fkClientId"', '=', 'c.id')
        ->where('iup."fkUserId"', '=', $authUser->getId())
        ->orwhere('p."fkSuperUserId"', '=', $authUser->getId())
        ->where('p.status', '=', 'active')
        ->where('c.status', '=', 'active');

I get:

SELECT p.id , p.uniq_id , p.name , p.description , p."startDate" , p."endDate" , p.latitude , p.longitude 
FROM projects p 
INNER JOIN int_users_projects iup ON p.id = iup."fkProjectId" 
INNER JOIN clients c ON p."fkClientId" = c.id 
WHERE iup."fkUserId" = ? OR p."fkSuperUserId" = ? AND p.status = ? AND c.status = ? 

But I want:

SELECT p.id , p.uniq_id , p.name , p.description , p."startDate" , p."endDate" , p.latitude , p.longitude 
FROM projects p 
INNER JOIN int_users_projects iup ON p.id = iup."fkProjectId" 
INNER JOIN clients c ON p."fkClientId" = c.id 
WHERE (iup."fkUserId" = ? OR p."fkSuperUserId" = ?) AND p.status = ? AND c.status = ? 

Offset is not options as per documentation

Hi,

As per documentation, we can use

// ... LIMIT 10
$statement->limit(10);

But if you go to LimitClause.php file, there is check "if (!is_int($number) || !is_int($offset)) {" which throws error if we do not pass 2nd argument. 👎

And btw event I pass both the arguments, there is not result. Please fix this.

get real sql from statement

Hello,

is there a way to get the real sql from the statement.

For example:


$selectStm = $slimPdo
->select()
->from('users')
->where('id','=',$id);

        $stm = $selectStm->execute();
        $data = $stm->fetchAll();

$mySql = $selectStm->getSql();


Your sincerly

Stephan

Get the PDO class/connection

Although Slim-PDO has almost every wanted feature, it doesn't cover all the MySQL (or other DB's) features. Is it possible to call the main \PDO class when needed?

Thanks. :)

Increase counter

Hi,

How can I perform this query:
UPDATE table SET count = count + 1 WHERE id = ?

Thanks.

Update table with existing value?

I looked set method of Slim\PDO\Statement\UpdateStatement class and it doesnt provide self column aritmetic operations such as count=count+?, count=count-? etc. It could be flexible implement of this method with 2d arrays.

Thnx for repo.

limit() clause does not work directly from form values

Current limit() clause use is_int() to check params. I use $request->getParsedBody()['rowCount'] and it does not work. I then must cast it to int.

Please include this in limit() document in case someone has the same problem.

select count(*) ?

Hi !

Thank you for you great PHP Class. But how can make a select count ?

Here is an sample with simple PDO

$sql = "SELECT count(*) FROM table WHERE foo = bar";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();

Delete after Select request

There's an issue when you delete a row that you selected before.

After having selected my user, I want to delete the row.

So first, I select him

$usr = $pdo->select(['id'])
               ->from('users')
               ->where('username', '=', $args['username'])
               ->where('password', '=', $args['userpsw'])
               ->where('token', '=', $args['usertk'])
               ->execute()->fetch();

So, $usr['id'] returns me an id (14 in my actual case)

and next, I want to delete him

$pdo->delete()
              ->from('users')
              ->where('id', '=', $usr['id'])
              ->execute();

Slim throws an exception without code error, but when I put another id that was not selected before (like $usr['id']+1, everything work well.

Is there a way to close select request in order to delete it after?
Thanks

Question

Would it be possible to add the ability to execute raw SQL commands with this package?

Problems with WhereClause

I need where clause like this
$statement->where('DATE(myDate)', '>=', 'DATE(NOW())');

But if we look at what happened with
$statement->__toString()
we will see
TE(myDate) >= ?

The problem in this expression:
return ' WHERE '.ltrim(implode('', $args), ' AND');
ltrim removes all letters listed in $character_mask.

string ltrim ( string $str [, string $character_mask ] )
http://php.net/manual/en//function.ltrim.php

Creating WHERE clauses

Hello,

How can I make a query like this
SELECT * FROM table WHERE field1 = 1 AND field2 = 2 AND (field3 = 3 OR field4 = 4);

Thanks.

INSERT documentation update

Please update README.md and INSERT.md documentation, the argument for INSERT execute() must be TRUE or undefined to return insert id.

This looks wrong:
$insertId = $insertStatement->execute( false );

As it stands in source code, the value must be TRUE or undefined.

/**
 * @param bool $insertId
 *
 * @return string
 */
public function execute($insertId = true)
{
    if (!$insertId) {
        return parent::execute();
    }
    parent::execute();
    return $this->dbh->lastInsertId();
}

what about transaction in pdo?

Hi bro,
I'd love to know if you can provide the function, which supports the PDO transaction, simply put, the commit, rollback etc.

Insert or Update

Hello,

I'm looking for a way to write a combined update.
Example:

INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

Your sincerly

Stephan

Master slave database?

When I use ‘select’, I need to use the slave database and how to configure the master slave database.?

ON DUPLICATE KEY UPDATE

Hello everyone,

I'm having some issues to implement a "ON DUPLICATE KEY UPDATE" sentence using Slim-PDO.

Is it supported?
I tried to find in documentation but no luck. Also tried to improvise but no luck either.

Best regards,
DF

INSERT IGNORE

I'd like an ability to modify the command to INSERT IGNORE.

statement->limit()

Hi,

$statement->limit($number, $offset); not working properly.
In MySQL this expression has the format [LIMIT [offset,] rows]

You have mixed up the parameters.
$this->limit = intval($number).' , '.intval($end);

MsSQL Limit Clause

I don't have a suggestion for this one yet, but if something dawns on me, I'll create a pull request. So the select limit clause needs a check for MS SQL as it use a differen SELECT TOP n * FROM table; notation.

array_merge of $options in Database::__construct() loses keys.

According to http://php.net/manual/en/function.array-merge.php, the keys that are being set in https://github.com/FaaPz/Slim-PDO/blob/master/src/PDO/Database.php under the __construct function, are being renumbered, so they are being passed to the parent constructor using the incorrect values.

I'd suggest using "$options += array(default options)" statement instead, which preserves the numeric keys, while allowing what I believe is the intended behaviour here.

Joining is only available on Select statements

Hi Fabian,

It looks like the join clause is only available on select statements, but should be available on SELECT, UPDATE, INSERT and DELETE for cross table query constraints. It's a simple fix but should be slated for 2.0.

Awesome work

I've been using this package and it blows Propel and Doctrine out the water in terms of getting started and pure performance.

Not an issue ;) just wanted to say thanks for the good work.

Error executing query

Hello. this query is not working. I believe is trying to bind permissions.account_id

$selectStatement = $this->pdo->select()
    ->from('accounts, permissions')
    ->where('accounts.id', '=', 'permissions.account_id')
    ->where('permissions.company_id', '=', $company_id)
    ->groupBy('accounts.id');   

how are you guys dealing with this?

Multiple "whereIn" statements causes problems

I have two whereIn statements, and the second one causes the entire SELECT statement to fail.

My code:

$property_classes = ["2-11"];
$zoning_classes = ["RT-4"];

$select = $pdo->select(["*"])
		 ->from("property_table AS p");
$select->whereIn("property_class_15", $property_classes);
$select->whereIn("zone_class", $zoning_classes);

print_r on $select outputs:

[values:protected] => Array
                (
                    [0] => RT-4
                    [1] => 2-11
                    [2] => TRUE
                )

            [table:protected] => propertytaxes_09_15_combined2 AS p
            [whereClause:protected] => Slim\PDO\Clause\WhereClause Object
                (
                    [container:protected] => Array
                        (
                            [0] =>  AND zone_class IN ( ? )
                            [1] =>  AND property_class_15 IN ( ? , ? )
                            [2] =>  AND ST_Intersects(p.geom, ST_Transform(ST_MakeEnvelope(-87.7193069458008,41.931360904903066,-87.7081596851349,41.93654878172632, 4326), 3435)) = ?
                        )

                )

Notice that property_class_15 has two ? yet it only has 1 corresponding value in the values array (2-11). If the property_class_15 has 2 corresponding values, then there will be three ?.

Why is the second whereIn statement increasing the number of placeholders by 1?

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.