PHP
Using rowCount with the sqlite driver of PDO.
0If you are reading this post, you’re probably facing an issue with sqlite and pdo that prevents you from using the rowCount method on a PDOStatement instance.
Apparently the new API of sqlite does not allow pdo to get this information. At work we faced this issue so I wanted to share it the web
In order to do this we need to overwrite the default PDOStatement. To do this we need to start by extending PDO and Using the ATTR_STATEMENT_CLASS flag in order to use our tweak statement class.
PDO::ATTR_STATEMENT_CLASS: Set user-supplied statement class derived from PDOStatement. Cannot be used with persistent PDO instances. Requires array(string classname, array(mixed constructor_args)).
Database.class.php
class Database extends PDO
{
function __construct(string $dsn,$username = null,$password = null,array $driver_options = null)
{
parent::__construct($dsn, $username, $password, $driver_options);
if($this->getAttribute(PDO::ATTR_DRIVER_NAME) == "sqlite") {
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array( 'Statement', array( $this )));
}
}
}
Statement.class.php
class Statement extends PDOStatement
{
/**
*
* @var \Pdo
*/
private $_pdo;
/**
*
* Constructor
*
* @param \Pdo $pdo
*/
protected function __construct($pdo)
{
$this->_pdo = $pdo;
}
/**
* Returns the number of rows affected by the last SQL statement
*
* @link http://www.php.net/manual/en/pdostatement.rowcount.php
* @return int the number of rows.
*/
public function rowCount()
{
// In case of sqllite, we don't have the row count
// So we have to re run the statement in order to get the row count
// And to avoid to move the current cursor
$statement = $this->_pdo->query($this->queryString);
return count($statement->fetchAll());
}
}
As you can see we use the count() function on the sqlite workaround, using this on very large dataset can be a really bad idea. We could create a count query here instead but It would’nt work on all query(complex group by’s etc..). If you are only using simple queries you can rewrite the query on the go to issue a count instead (if you need inspiration ).
Since we check for the driver on the PDO constructor will not be used on other drivers than sqlite.
Have fun.
Related Posts:
How to generate a word docx from a template with PHP ?
21Hey folks,
A lot of clients of mine asked for docx generation in the past.
The only solution that I knew of in PHP is the SOAP client phplivedocx.
first of all It was kinda slow and I didn’t want to relly on a service and more importantly It was missing the “nested block” feature.
So I decided to create my own class !
Have fun & fork me if you need another feature !
http://github.com/djpate/docxgen
DOCXGEN
Features
- Create valid docx based on a template
- Nested blocks on infinite levels
How to create your template
Simply open up word 2007+
If you want to map a single field you can just use #NAME# but you could use anything you like since it’s just a search & replace
To create a block
[start blockname] your content [start somenestedblock] [end somenestedblock] [end blockname]
- blockname should be unique
- blockname has to match w+ reg ex (a-zA-Z_)
- fields mapped in block has to be unique
Please check out full template in the repo
How to setup
require("phpDocx.php"); $phpdocx = new phpdocx("mytemplate.docx");
How to assign values
$phpdocx->assign("#TITLE1#","Hello !"); // basic field mapping $phpdocx->assignBlock("members",array(array("#NAME#"=>"John","#SURNAME#"=>"DOE"),array("#NAME#"=>"Jane","#SURNAME#"=>"DOE"))); // this would replicate two members block with the associated values $phpdocx->assignNestedBlock("pets",array("#PETNAME#"=>"Rex"),array("members"=>1)); // would create a block pets for john doe with the name rex $phpdocx->assignNestedBlock("pets",array("#PETNAME#"=>"Rox"),array("members"=>2)); // would create a block pets for jane doe with the name rox $phpdocx->assignNestedBlock("toys",array("#TOYNAME#"=>"Ball"),array("members"=>1,"pets"=>1)); // would create a block toy for rex $phpdocx->assignNestedBlock("toys",array("#TOYNAME#"=>"Frisbee"),array("members"=>2,"pets"=>1)); // would create a block toy for rox
How to save
$phpdocx->save("somefile.docx");
More info
Why this pclzip ?
I’m using pclzip for the zip process because the zip utility provided with php can cause issue with office
What’s the licence ?
GPL
Anything else ?
I’m using three function from the TBS library so congrats to them
Related Posts:
How to make cross-domain ajax request using jsonp & jquery
1As you may know AJAX request cant be done across domain (even across subdomain). This is a security feature but sometimes It can pretty usefull to make call between domains.
Luckily for us AJAX allows us to make cross domain request for javascript contents. That is how JSONP works, basicly instead of passing plain json you pass json inside a javascript function.
I’m going to show you how you can do this very easily using jQuery.
first of all make the call using jquery.
$.getJSON("http://someurl/somepage.php?jsoncallback=?",function(data){
alert(data.msg);
});
As you can see we have to set jsoncallback=? in the url for this to work.
Now In your php file.
<?php
$array = array("msg"=>"hello"); //some bogus data
echo $_REQUEST['jsoncallback']."(".json_encode($array).")";
?>
The output will be something like :
jquery65456456456({“msg”:”hello”})
As you can see It now looks like a javascript function.
That’s all there is too it !
Related Posts:
How to setup Xdebug on ubuntu 10.10
2Hello,
I’ve been trying to figure out how to actually set up Xdebug on my php configuration but I never managed to get the “Styled” version of Xdebug.
I finally figured out why so I decided to share it
First install xdebug with pecl
sudo pecl install xdebug
Then create a xdebug config file and add a link to your .so file
sudo nano /etc/php5/apache/conf.d/xdebug.ini # then add zend_extension = /usr/lib/php5/20090626+lfs/xdebug.so
Now here is the part that I couldn’t figure out.
In your php.ini file you need to enable display_errors & html_errors.
sudo nano /etc/php5/apache/php.ini # then look for display_errors & html_errors and set it to On.
finally restart apache
sudo /etc/init.d/apache2 restart
You’re all set !
Related Posts:
How to write a complete OAuth Provider in PHP5
73Today I’m going to talk about a subject that doesn’t have a lot of coverage on the web.
There is a lot of tutorials about how to use OAuth authentication for twitter services or google & such but there is not a lot of information on how to actually make your own oauth provider.
Now if you are reading this post you probably allready know why Oauth is good and what his purpose is but you can check out some info here.
On this post I’m going to use an basic example case and we will go from nothing to actually handling api calls.
You can download the full source code of a working provider from here. It includes the provider described here as well as a basic client to help you test it out…
Related Posts:
gmail, yahoo & live messenger contact inviter script
20Howdy,
you guys have probably noticed that most of the contact inviter script out there were broken now because most of the new api’s only support Oauth protocol instead of the good ol’ login / password authorization.
It’s great because now you don’t have to give the those website your login information but It is a bit more complicated for us developers to set it up so I’ve decided to create a small set of classes that will allow you to easily implement such a feature on your website.
First off all, you can check out the simple proof of concept by checking out the demo here and getting the script on gitHub here.
Some people who may know my blog will notice that I am in no way a designer so It doesnt look amazing but it works and that’s what this article is about ! ( if someone feels like he could make it look better you can get the code from github. see at the end of the article for more info).
Ok so now the fun stuff.
(more…)
Related Posts:
Import Gmail Address book with Curl and PHP
13Hello everyone,
I had to write a class to import a Gmail address book so I decided to share.
As you will see it’s fairly simple.
<?php
class GoogleContact
{
private $email;
private $pass;
private $auth;
public function __construct($email, $pass){
$this->email = $email;
$this->pass = $pass;
}
public function login(){
$url = "https://www.google.com/accounts/ClientLogin";
$post = array("accountType"=>"HOSTED_OR_GOOGLE","Email"=>$this->email,"Passwd"=>$this->pass,"service"=>"cp","source"=>"GoogleContact");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$retour = curl_exec($curl);
if(preg_match("/Error/",$retour)){
return false;
} else {
$auth = explode("Auth=",$retour);
$this->auth = $auth[1];
return true;
}
}
public function fetchContact(){
$authHeader = array('Authorization: GoogleLogin auth='.$this->auth);
$url = "http://www.google.com/m8/feeds/contacts/default/full?max-results=1000";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $authHeader);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$retour = curl_exec($curl);
$matches = array();
preg_match_all("/address='([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})'/i",$retour,$matches);
return $matches;
}
}
?>
And you can use this way :
<?
$g = new GoogleContact("djpate@gmail.com","youwish");
if($g->login()){
$contacts = $g->fetchContact();
print_r($contacts);
} else {
echo "Access denied";
}
?>
Have fun guys !
Related Posts:
How to add image tagging the facebook way !
34Updated post here
Today I want to show you how to make a image tagging function on your website.
It works about the same way than facebook does (or a least the way it worked some times ago because I deleted my facebook account)
Basicly you take an image and you “tag” people or stuff in it by marking what you want to tag with a rectangle.
This example is just a proof of concept and will give you a good idea on how to make it better for your website.
This script requires jquery and jquery-ui with draggable and resizable function(it’s included in the source).
note : I didnt have time to test it on IE so let me know if it works for you…
Here is the Demo and the Source.
Related Posts:
How to : Create a simple url shortener script is a few minutes
27Hello all,
First let’s explain the basics of what we are trying to do.
We’ll build a script that will replace any type of url to a tiny url so it’s easier to post or be untraceable.
For example this *long* google maps url
http://maps.google.fr/maps?f=q&source=s_q&hl=fr&geocode=&q=white+house&sll=46.75984,1.738281&sspn=10.178118,28.54248&ie=UTF8&z=15&iwloc=A
could become
http://your.site/v/12345
you can check it out here : http://www.djpate.com/portfolio/shortURL/create.php
and download the source code here
This is not very hard to do but it’s nice tutorial for beginners.
Related Posts:
How to : Pdf thumbnails with php
0Hello,
I’ve just worked on something for a project of mine and I wanted to share this code with you.
It’s nothing new but good to know…

Last comments