Giter Site home page Giter Site logo

izniburak / pdox Goto Github PK

View Code? Open in Web Editor NEW
298.0 27.0 106.0 196 KB

useful query builder class that works with PHP PDO class for simple access your data.

Home Page: http://burakdemirtas.org/pdox-kullanisli-pdo-sinifi-php/

License: MIT License

PHP 100.00%
php sql query-builder

pdox's Introduction

PDOx

 _____  _____   ____       
 |  __ \|  __ \ / __ \      
 | |__) | |  | | |  | |_  __
 |  ___/| |  | | |  | \ \/ /
 | |    | |__| | |__| |>  <
 |_|    |_____/ \____//_/\_\

Fast, efficient and useful Query Builder and PDO Class for #PHP

Total Downloads Latest Stable Version Latest Unstable Version License

Install

composer.json file:

{
    "require": {
        "izniburak/pdox": "^1"
    }
}

after run the install command.

$ composer install

OR run the following command directly.

$ composer require izniburak/pdox

Example Usage

require 'vendor/autoload.php';

$config = [
	'host'		=> 'localhost',
	'driver'	=> 'mysql',
	'database'	=> 'test',
	'username'	=> 'root',
	'password'	=> '',
	'charset'	=> 'utf8',
	'collation'	=> 'utf8_general_ci',
	'prefix'	 => ''
];

$db = new \Buki\Pdox($config);

$records = $db->table('users')
		->select('id, name, surname, age')
		->where('age', '>', 18)
		->orderBy('id', 'desc')
		->limit(20)
		->getAll();

var_dump($records);

Docs

Documentation page: PDOx Docs

Support

izniburak's homepage

izniburak's twitter

Licence

MIT Licence

Contributing

  1. Fork it ( https://github.com/izniburak/pdox/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

pdox's People

Contributors

alitelli avatar const-undefined-man avatar emresaracoglu avatar garetbot avatar halillusion avatar izniburak avatar meilhamfadil avatar robertgrubb avatar sineld 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

pdox's Issues

new where clause functions

hi @izniburak

how about having clean whereNull and whereNotNull

  public function whereNull($where)
  {
    $where = $where . ' is null';
    if (is_null($this->where))
      $this->where = $where;
    else
      $this->where = $this->where . ' ' . 'and ' . $where;
    return $this;
  }
 
// will produce ``` where tbl.colmn is null```

  public function whereNotNull($where)
  {
    $where = $where . ' is not null';
    if (is_null($this->where))
      $this->where = $where;
    else
      $this->where = $this->where . ' ' . 'and ' . $where;
    return $this;
  }

// will produce ``` where tbl.colmn is not null```

Actually, I really missed these functions in my last project, so i had to extend your class.

Thanks !

UPDATE return false

In my conditions I check if the query returns true.
But while the query is well executed in Mysql, Pdox returns false ...

Example Class :
`public function update($table, $paramname, $content, $token){

    $this->name = $paramname;
    $this->content = htmlspecialchars($content);
    $this->token = $token;

    $data = [
        $this->name => $content
    ];

    $quy = $this->database1->table($table)->where('active', 1)->update($data);

    if ($quy){

        return true;

    }else{

        return false;

    }
}`

Example Code :
`if (isset($_POST['token']) && isset($_POST['msg_title']) && isset($_POST['msg_content']))
{
$token = $_POST['token'];
$content = $_POST['msg_content'];
$content1 = $_POST['msg_title'];

$request = $config->update("settings", "msg_title", $content1, $token);

if ($request === true){

    $request1 = $config->update("settings", "msg_content", $content, $token);

    if ($request1 === true){

        $result['status'] = 42;
        $result['message'] = "Update with Success !";

        echo json_encode($result);

    }

    $result['status'] = 40;
    $result['message'] = "Problem with SQL request.";

    echo json_encode($result);

}else{

    die(var_dump($request));

    $result['status'] = 44;
    $result['message'] = "You are not authorized.";

    echo json_encode($result);
}

}`

Thanks for your help.

show/hide error

hi.
can i set error as false in config to do not call error() in production ?
:)

LIKE İşlemleri

Merhaba,

LIKE İşlem sonucunu ekrana nasıl yazdiliriyor?

$db->like('title', '%burak%');

Bunun için foreach kullanılmıyor sanırım(?)
Teşekkür ederim

line 493 and line 518 "==" should be "===" in pdox.php

public function get($type = false)
  {
    $this->limit = 1;
    $query = $this->getAll(true);

    if($type == true)
      return $query;
    else
      return $this->query( $query, false, (($type == "array") ? true : false) );
  }

should be:

public function get($type = false)
  {
    $this->limit = 1;
    $query = $this->getAll(true);

    if($type === true)
      return $query;
    else
      return $this->query( $query, false, (($type == "array") ? true : false) );
  }

this error leads to "get('array')" function returning a query string instead of array database record

Connect with Heroku postgres

I am working with Heroku and I use pdox in my app. I'm having trouble connecting to Heroku's postgres database using Pdox, I believe the solution would be to pass the connection Heroku gives me so that Pdox can work, I see how Heroku works:

<?php
# This function reads your DATABASE_URL configuration automatically set by Heroku
# the return value is a string that will work with pg_connect
function pg_connection_string() {
  return "dbname=abcdefg host=****.amazonaws.com port=5432 user=**** password=**** sslmode=require";
}
 
# Establish db connection
$db = pg_connect(pg_connection_string());
if (!$db) {
    echo "Database connection error."
    exit;
}
 
$result = pg_query($db, "SELECT statement goes here");

I needed to pass $db to Pdox instead of a $config, which is the best way I could do this:

$dbPdox = new \Buki\Pdox($db);

php Version

Hi,
on which versions of php >= 7 does the class run?

about leftJoin

Merhaba,
"leftJoin('foo as f', 't.id', 'f._t_id')" bu "ON t.id = f.t_id "
ben "ON t.id = f.t_id AND t.active= 1" için leftJoin içerisinde nasıl yazılmalı?

Tablonun Ortalamasini Alabilmek (AVG)

Merhaba,

Tablo Sayilar'ın için de yer alan yuzdelikBirimler kısmının ortalamasini alabilmek için;

$genelOrtalamasi = $db->table('Sayilar')->avg('yuzdelikBirimler')->getAll();

sorgusundaki sonucu nasil yazdırmalıyım?
Teşekkürler

İki Farklı Tablodaki Farkı Bulabilmek

Merhaba,

$db->select('DISTINCT id')
->table('test as t')
->join('foo as f', 't.id', 'f.t_id')
->where('t.status', 1)
->getAll();

Yukarıdaki sorgu işleminde iki farklı tabloyu birleştirmeyi sağlayabiliyorum ancak tam olarak amacim her iki tabloda olan verileri almak değil, test tablosunda olan verinin foo tablosunda karşılığı yok ise, test tablosundaki ID numarasini yazdirmak istiyorum.

Özet olarak; test tablosunda 235135 nolu değerin, foo tablosunda karşılığı yok ise, yazılmasını sağlamak.

Bunu PDOx ile nasıl sağlayabilirim?

SQL error on CREATE TABLE using QUERY method

When i use query method to create a table, this return me SQL ERROR without any description;

$this->getBdd()->query("CREATE TABLE IF NOT EXISTS my_table (
        id SERIAL NOT NULL,
        user_id integer NOT NULL,
        coordx double precision NOT NULL,
        coordy double precision NOT NULL,
        geom GEOMETRY NOT NULL,
        create_at timestamp without time zone NOT NULL,
        PRIMARY KEY(id)
        )")->exec();

As no rows are affected when creating any table returns 0

I have found a "partial" solution commenting some lines of the method exec()

    public function exec()
    {
        if (is_null($this->query)) {
            return null;
        }

        $query = $this->pdo->exec($this->query);

//        if (! $query) {
//            $this->error = $this->pdo->errorInfo()[2];
//            return $this->error();
//        }

        return $query;
    }

I will continue working on my fork and if I find a viable solution I will comment here.

'Like' Olduğunda 'Where' Önemsiz

Merhaba,

Aynı sorgu talebinde LIKE ve WHERE mevcut ise; sorgu sonucunda WHERE işlevini kaybediyor.

Örnek:

 $Gets = $db->table($ornekTablo)
->where('aktif', 1)
->like('terim', '%' . $aramaTerimi. '%')
->orLike('terim2', '%' .$aramaTerimi.%')
->limit(10)
->offset($offsetVerisi)
->getAll();

Aranmak istenen terim aktif olmasa dahi sonucta gösterimi sağlanıyor. LIKE İptal edildiği takdirde aktif olmayan terimlerin gösterilmiyor.

Teşekkürler

count(): Parameter must be an array or an object that implements Countable query->fetch()

i try use query method;

->query("SELECT nis_rad,matric,ROUND(ST_distance(suministros.geom,centro_transformacion.geom)::numeric,2) AS distancia_mts,centro_transformacion.circuito,centro_transformacion.propietari,centro_transformacion.referencia,ROUND(centro_transformacion.cant_salbt::numeric,0)
FROM public.geo_tbl_suministros AS suministros, public.geo_tbl_transformadores AS centro_transformacion
WHERE nis_rad = ? 
AND centro_transformacion.matric = ?", [$nis,$ct])->fetch();

and recive this error message;

count(): Parameter must be an array or an object that implements Countable Pdox.php on line 752

I have corrected this with the following code

Before;

$this->numRows = count($result);
return $result;

After

if(is_array($result)){
    $this->numRows = count($result);
}
return $result;

port

how about add port configuration?

How cache works in this query builder ?

Hi
First of all thank you so much for making this AWESOME query builder :)
I was going through code, and i found some code related to cache
can you please tell me how exactly CACHE works in this query builder

Thanks.

Error

Hi

Thank you for useful class
please check line 63

$collation = $config['collation']
it's missing ";"

Toplama İşlemlerinde Önbellek

Merhaba,

Sorgu işlemlerinde önbelleği kullaniyorum ve oldukca yararli fakat tablo içerisindeki tüm verilerin sayısını ögrenmek için cache(3600) komutunu eklediğim takdirde tablo toplama işlemi örneğin 43.000 ise bi anda 0 (sıfır) düşmekte olup ve önbellek kaydını 0 şeklinde almaktadir.

$db->numRows(), önbellek formatını anlamadiği için mi bu durum söz konusu yoksa benim mi hatam var?

Teşekkürler

Using distinc

Hi.

How can i use DISTINC with this library?

Thank you

Toplama İşlemi (SUM)

Merhaba,

Birkaç satırda yer alan sayılari toplamak için aşağidaki kod diziminde hata yapıyorum, acaba hata tam olarak nerede?

Düşünceme göre total_row kısmında hata yapıyorum ama emin değilim.

$arsivlenmisDokumanSayisi = $db->table('Dokumanlar')->sum('Arsivlenmis', 'total_row');
foreach ($arsivlenmisDokumanSayisi as $arsivlenmis) {
    echo $arsivlenmis->total_row; 
}

Teşekkürler

Sorguyu->Pdox Cevirme

Merhaba

Asagidaki sorguyu, Pdox'e göre düzenlemeye çalıştım ancak başarılı olamadim, yardımcı olabilir misiniz?

$sql = "SELECT * FROM `tabloA` WHERE (`testA` != '' AND `testB` != '')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) { 
   ...

Query sorguları hakkında

$db = new \ThirdParty\Pdox\Pdox(TYH_DB);
$db->pdo->exec("SET NAMES UTF8");
$veriler            = $db
                        ->query("SELECT COUNT(id) FROM ".$tablo);
                        print_r($veriler[0]); exit;

şeklinde bir sorgu yaptığım zaman bana çıktıyı

stdClass Object ( [COUNT(id)] => 3 )
şeklinde veriyor. Fakat ben bu veriyi almak istediğim zaman
echo $veriler[0]->COUNT(id);
dediğimde php parantezlerden dolayı onu fonksiyon zannediyor ve objenin içerisine erişemiyorum.
Yardımcı olur musunuz :)

Version Info

Hi,
maybe you could insert a Versioninfo somewhere in files/packet.
It would make Version-Control in Projects easier.
thx

SQLite Ile Veri Cekimi

Merhaba,

<?php 
require 'vendor/autoload.php';
$config = [
    'host'      => 'localhost',
    'driver'    => 'sqlite',
    'database'  => 'test.sqlite',
    'username'  => '',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_general_ci',
    'prefix'     => ''
];
$db = new \Buki\Pdox($config);
$records = $db->table('sqliteTest')->getAll();
foreach($records as $record)
{
    echo $record->Area. '<br />' ;
}

Bununla test.sqlite adindaki veritabani dosyasi icerindeki verileri ekrana yazdiramiyorum.
Veritabani dosyasi yada tablo adininda degisiklik yapildigi takdirde Database Error ile karsilasirken dogru bilgilerle beyaz ekran aliyorum.

SQLite ile veri cekiminde nerede hata yapiyorum?

Tekrardan tesekkurler,
mutlu gunler

Datetime sorguları hakkında

where kısmında created_at < CURRENT_DATE - INTERVAL 3 DAYS bulunan sorguyu pdox ile kullanamadım.

$db->table("hesaplar")->where("created_at" '<', 'CURRENT_DATE - INTERVAL 3 DAYS')->limit(1)->get();

CURRENT_DATE - INTERVAL 3 DAYS tırnaklar içinde gittiği için sorgu gerçekleşemiyor. Bu tarz sorgular konusunda $db->query() kullanımı dışında önerileriniz için şimdiden teşekkürler.

space

hi,
Please check the following code:
`
$values = array();

$values['string_text'] = " Hi"; // 4 Space

$string_id = 1;

$PDOx->table( 'strings' )->where( 'string_id', $string_id )->update( $values );

`

After implementation
Field value [string_text] = " Hi" // 1 Space
How to solve this problem?

When do I support preprocessing?

Occasionally see you write this class about PDO operation, very easy to use. If we support preprocessing, it will be perfect.

Enhancement Request - FETCH_CLASS

Hello,

I enjoy the code, I had to customize locally to add the ability to fetch by a custom class.

$sql->fetchAll(PDO::FETCH_CLASS, $this->class_name)

You might want to consider as a 3rd option to return data.

Thank You !

Join Issue

Merhaba,
Dökümantasyonda eksik kalan join kısmını tamamlamanızı rica ediyorum.

Birden Fazla Veri Ekleme

Merhaba,

Birden fazla veriyi tek seferde tabloya eklemek PDOx ile mümkün mü?
Eğer mümkün ise örnek verebilirsiniz?

Mutlu haftasonu diliyorum.

Var Olan Verinin Üstüne Ekleme

Merhaba,

Tabloid yer alan miktarin üzerine belirlenmiş bir miktarin daha eklenmesini istiyorum. Klasik sorguda yapilan bu tarz işlemi, PDOx ile nasil yapilabilir?

Denediğim sorgu:

$data = [
    'kullanilanAlan' => 'kullanilanAlan' + 100000
]; $db->table('users')->where('user_id', 2)->update($data);

Teşekkürler!

need help

I tested out this class and have a problem.
I dont use composer.

the files are like this:

root/page.php

  • include inc/func.inc.php
  • some html, db-access via pdox

root/inc/func.inc.php

  • include db.inc.php
  • contains functions for db-access

root/inc/db.inc.php

  • include Pdox.php
  • include Cache.php
  • define $config

root/inc/Pdox.php
root/inc/Cache.php

calling page.php executes the db-acess and shows content
calling a function from func.inc.php to get a value from db crashes the page.php

its for replacing the PdoDB-Class in this Projekt what didnt work with php >7.

please give me a help

SQLite Ile Tablo Gosterimi ve Veri Ekleme

Merhaba

Onceki yardimlariniz icin tesekkur ederim,
SQLite veritabani icerisine veri ekleme/guncelleme yapabilirken, veri ekleme kisminda hatami bulamiyorum.

$browers = $db->table('albums')->getAll();
foreach($browers as $brower) {
    echo $brower->AlbumId;
} 

Ayrica SQLite veritanindaki tablolari ekrana PDOx ile nasil yazdirilabilir? Tablo yazdirmak icin SQL giris alani olmadigi icin nasil bir yol izlenmelidir?

Ornegin;

Album, Artist, Customer, Employee, Genre, Invoice, InvoiceLine, MediaType, Playlist, PlaylistTrack, Track.

Tablo isimlerini yazdirmak eger mumkun ise tabloya ait verilerin (tablo boyutu, satir sayisi vs) ekrana yazilmasi mumkun mu?

Yardimlariniz ve vakit ayirdiginiz icin en icten dileklerimle tesekkur ederim.

Tablodaki Aynı Verileri Eleme

Merhaba,

Aynı tablo içerisinde yer alan aynı veriler birden fazla ise ve yazırma işleminde, aynı veriden sadece bir kere yazılmasını sağlamak için nasil bir method uygulamak gerekiyor?

Örneğin;

id users
1 Emre
2 Burak
3 Burak
4 Katya
5 Kayta

Çıkış:

Emre
Burak
Katya

Update Set NULL value

I am trying to set a value as null but its not working

$db->table('users')->where('id', 1)->update(['phone' => NULL]);
Database Error

Query: "UPDATE users SET phone= WHERE id = '1'"

Error: 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 'WHERE id = '1'' at line 1

is it possible to make it work without using query method

where statement

is it possible to use the where-clause
$where = [
'name' => 'Burak',
'age' => 23,
'status' => 1
];

also for
'age' > 23,

?

Truncate Table [Error]

Merhaba,
Veritabanina ait tabloyu kaldirma değil, sadece içini boşaltmak istediğimde bu hata ile karşılaşiyorum.
Klasik PDO sorgusun bu işlemsiz hatasiz olarak çalışmakta, gözden kacirdigim noktayi göremiyorum

$test = $db->query('TRUNCATE TABLE ?', ['testTablosu']);
	if ($test) {
		echo "<div class='notice notice-success'>All databases delete from MDM</div>";
	} else {
		echo "<div class='notice notice-danger'>All databases not delete from MDM</div>";
	}

Cikisi:

Database Error
Query: "TRUNCATE TABLE 'testTablosu'"
Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''testTablosu'' at line 1

Bunun sebebi ne olabilir?

multiple queries

allows multiple queries ?, insert and update also begin transaction , commit and rollback inside? , do you have an example ?

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.