Joomla Failed to Read Session Data Native.php

Using PHP Data Objects

  • Knowledge needed: Some noesis of PHP and SQL is useful
  • Requires: A spider web server (such equally Apache) with PHP loaded, and a relational database management organisation capable of PDO connectivity (such equally MySQL); ODBC and Doctrine two are optional extras
  • Project Time: 1-three hours (or more than, depending on your serendipitous learning path and capacity)
  • Source file

This commodity beginning appeared in event 231 of .net magazine.

Dynamic website and application evolution seems more than commonplace than static website creation these days, and with dynamic evolution comes the need to store data.

A popular database direction arrangement used aslope the PHP language is the MySQL database, with Microsoft SQL, PostgreSQL and Oracle also being adequately mutual. The PHP group of developers initially eased connecting between PHP and the database systems using database-system specific functions such as:

MySQL: resource mysql_query ( cord $query [, resources $link_identifier ] )
Microsoft SQL: mixed mssql_query ( string $query [, resources $link_identifier [,
int $batch_size = 0 ]] )
PostgreSQL: resource pg_query ([ resources $connection ], string $query )
Oracle Database: bool oci_execute ( resource $statement [, int $mode = OCI_
COMMIT_ON_SUCCESS ] )

Equally you lot can encounter from the definitions they have no standardised form, then if you lot had to modify your database system from Oracle to MySQL you'd accept to piece of work through your lawmaking and change how you connect to your database. Information technology'south also a thorn in the side of learning virtually database connectivity in PHP: you can't just transfer your knowledge from, for case, PostgreSQL to Microsoft SQL.

01. The PHP Data Objects (PDO) philosophy

Thankfully a database connectivity saviour does exist in PHP – and this is in the form of the three letter acronym PDO, which stands for PHP Data Objects. The idea of the PDO library is that it provides a standardised foundation on which you can connect to any relational database management system (RDBMS) that tin be queried using SQL.

With a little luck your PDO creation script should create a valid table, like the one above, in your database

With a footling luck your PDO cosmos script should create a valid table, like the one in a higher place, in your database

At the fourth dimension of writing this includes CUBRID, Firebird, Interbase, IBM DB2, Informix, Microsoft SQL Server, MySQL, Oracle, PostgreSQL, SQLite, 4D – and any database that's connectable via ODBC.

Taking a quick conceptual example of the changes, we would previously take seen:

<name-of-rdbms>_query($sql);

We at present see a standardised set of functions, which looks a bit similar this:

$conn->query($sql);

Just that'south quite plenty theory for now – let's take a look at this powerful library in action! There are 2 singled-out aspects to PDO, the first being the connection – which is clearly a required element – while the second side is the querying chemical element.

02. Connecting to a database management system

Earlier we query any information we must connect to an already installed and set-upward database direction system. Nosotros'll connect to a MySQL database, which is running on localhost, for the first example:

PDO('mysql:host=localhost;dbname=yourdbname', 'username', 'countersign');

Permit'south compare that with connecting to a PostgreSQL database:

w PDO('pgsql:host=localhost;dbname=yourdbname', 'username', 'password');

The connections are standardised thanks to the first example using the same function, while the 2d employs the standardised data source name (DSN) system. You can start to run into how easy it is if you lot just want to switch from 1 database direction system to some other.

Drupal 7 has PDO behind its database abstraction layers. The official Drupal documentation on these is a great way to find out more about the integration

Drupal 7 has PDO behind its database abstraction layers. The official Drupal documentation on these is a neat way to discover out more nearly the integration

03. Querying and reading results

Querying data is initially more interesting than creating data, and every bit this is a tutorial on data connectivity rather than on SQL, nosotros'll get straight to querying and visit cosmos, insertion, updating and deletion later.

Nosotros're going to assume nosotros have a table called profile, which lists various details about users of a hypothetical web application. Every bit an example, let's run a quick contour fetch in SQL through PDO and so simply repeat out the full names. Discover how the query part can be used as an iterator – a function that stores a pointer, in retentivity, to the current element of an array (or result set in this example). When this is combined with a foreach loop it allows for a quick and easy method of accessing rows:

$conn = new $conn = new $conn = new $conn = neforeach ($conn->query("SELECT * FROM profile") every bit $row) echo
$row['fullname'];

Of course, this is quick and easy, only we hardly ever want to fetch all rows; therefore let us add some conditionals through variable injection. Here nosotros utilise a more robust querying method, which prepares the query and injects the variables:

$query = $conn->ready("SELECT * FROM profile WHERE username =
:username LIMIT 1");
$query->bindParam(":username", "knightofarcadia");
$query->execute();
$profile = $query>fetch( PDO::FETCH_ASSOC );
echo $profile['fullname'];

The code above will restrict the contour table search to just one profile with the user name knightofarcadia. Similar our first instance it'll only print out the full name after that – but you lot can certainly imagine building up an entire XHTML folio, which has the data passed to them.

The PHP Data Objects library helps power Facebook's HipHop Engine, which can reduce CPU usage on its web servers by up to 50 per cent

The PHP Data Objects library helps power Facebook'south HipHop Engine, which can reduce CPU usage on its web servers by up to 50 per cent

Nosotros might, even so, have more than than i row returned in our query, and therefore we have the adequacy of using the fetch method equally an iterator. Here we see a different query which returns a multiple row outcome ready:

$query = $conn->gear up("SELECT * FROM profile WHERE hometown = :hometown");
$query->bindParam(":hometown", "Wessex");
$query->execute();
foreach($query->fetch(PDO::FETCH_ASSOC) as $row) {
echo $row["fullname"];
}

The instance above volition search through the contour database and render all profiles that accept the hometown ready to Wessex. The fetch method is and then used to return all those results, and for a straightforward example we can simply print out the full proper name to screen – although this could exist a more than circuitous XHTML page operation.

04. Creating

Now, although I would advocate the cosmos of a database structure existence done in SQL directly into the database direction system, it is possible to dynamically create database tables using SQL prepared by PDO:

$createsql = $conn->prepare("CREATE TABLE profiles (username VARCHAR(64), fullname VARCHAR (128), hometown VARCHAR(128)"));
$conn->query($createsql);

Delight do call back that the query object in this case won't render anything of value considering it is a creation command. As already mentioned, it's worth trying to avert the use of dynamically creating tables in this way in a spider web application, although I can imagine it being used in 'run-once' web-based systems (such as server web applications installers), as well as in simple nonweb based server scripts.

Here's an object model that corresponds to the example PHP code used in this tutorial

Here'southward an object model that corresponds to the example PHP code used in this tutorial

05. Inserting

Inserting data is very important in a dynamic system, and particularly in contemporary Web ii.0 and Spider web 3.0 systems, which are orientated towards collaboration and co-operation – how can users interact if they accept no capability to store and share data? Therefore, allow'due south insert some data into our profile table thus:

$insertsql = "INSERT INTO profiles (username, fullname, hometown) VALUES (:username, :fullname, :hometown)";
$query = $conn->prepare($insertsql);
$query->bindParam(":username", "knightofarcadia");
$query->bindParam(":fullname", "Arthur Pendragon");
$query->bindParam(":hometown", "Wessex");
$query->execute();

Like the query function in the cosmos of tables, this execute function won't render annihilation of value considering it'southward simply an insert command to the database. You'll besides notice that we're using the 'prepare, bind and execute' technique in lodge to inject our variables into our SQL.

06. Updating

Updating, like inserting and deleting, is crucial in a collaborative system and PDO makes this like shooting fish in a barrel. Updating is quite similar to insertion:

$query = $conn->set up("UPDATE profiles Set up fullname = :fullname WHERE
username = :username");
$query->bindParam(":fullname", "Arthur Pendragoon");
$query->bindParam(":username", "knightofarcadia");
$query->execute();

The above block of code but replaces the full proper name of a user, only you'll detect that it'southward almost identical to the insertion code. We bind a provisional consequence, in this case the username, and we demark a setting event, in this case the new full name.

A simple relational database model of a normalised many-to-many relation – roughly the kind of structure Doctrine will build from an ORM definition

A simple relational database model of a normalised many-to-many relation – roughly the kind of construction Doctrine will build from an ORM definition

07. Deletion

Finally permit's accept a quick expect at deletion, which is frequently a simpler procedure than inserting or updating.

$query = $conn->ready("DELETE FROM profiles WHERE "username" =
:username );
$query->bindParam(":username", "knightofarcadia");
$query->execute();

The above SQL simply deletes a profile where we match on a username. Nosotros simply demark the username to the conditional variable.

08. Switching database direction system

Now, providing that the database table structure is identical and that we aren't using annihilation non-standardised inside a proprietary SQL system, nosotros can simply alter our data source proper name to point from one RDBMS – in our initial example the Microsoft SQL Server – to another (IBM DB2, for case). The whole lawmaking that we've done from then will work – without the demand of changing whatever SQL.

We volition get-go with our connection cord looking like this:

$conn = new PDO("sqlsrv:server=localhost;database=yourdbname",
"username",
"password");
$conn = new PDO("ibm:DRIVER={IBM DB2 ODBC Driver};DATABASE=yourd
bname;HOSTNAME=localhost;PORT=56789;PROTOCOL=TCPIP;","username",
"countersign");

Another of the PDO library's key users is MediaWiki, the app that powers all of the Wikipedia Foundation's projects

Another of the PDO library's key users is MediaWiki, the app that powers all of the Wikipedia Foundation's projects

09. Transactions

A transaction, in database terms, is where you salve upwards a set of queries to batch process at a later time. PDO provides a mechanism for building up transactions – only every bit these are highly dependent on the database direction arrangement, PDO transactions only piece of work when connecting to a subset of the RDBMS that PDO supports. If you lot endeavour to begin a transaction on an RDBMS that doesn't support transactions then you'll get a rather nasty PDO transaction. So allow's analyse some transaction lawmaking:

try {
$conn->beginTransaction();
$insertsql = $conn->set("INSERT INTO profiles (username, fullname,
hometown) VALUES ('wilfred', 'Wilfred Jones', 'Scarborough')");
$deletesql = $conn->gear up("DELETE FROM profiles WHERE username =
'username'" );
$conn->exec($insertsql);
$conn->exec($deletesql);
$conn->commit();
} catch (Exception $due east) {
$conn->rollBack();
// bulletin attainable with: $e->getMessage();
}

First nosotros begin a try-catch so that we can catch whatever bad exceptions, including those you lot may get through trying to connect to an RDBMS that does non take transaction support. We brainstorm a transaction with $conn->beginTransaction() before continuing building upwards our query executions, simply these won't be fully executed in the database until the $conn->commit() function is run, and they'll exist done in an efficient serial sequence – meaning you can do diverse other PHP processes between the execution commands with no touch on on the database.

If nosotros detect that the database doesn't support transactions then the transaction simply won't happen; if any other exception is thrown then we execute $conn->rollBack(), which will ringlet back any changes made by the transaction. It's worth noting that when connecting to a transactions-supported RDBMS, PDO will enter into an 'auto-commit' country, where each exec command is itself its own committed transaction; however, if you would like to work in a rubber way and so you can always use beginTransaction, and have access to the batch commit and the rollback functionality.

x. Problems with PDO

There are no real bug from the PHP perspective in using PDO. It's object oriented pregnant information technology is extensible and flexible, and it works with many systems in connectable manner. The problem comes when we consider that while the majority of relational database direction systems follow SQL standardisation (so helping u.s. switch from one system to another), many systems have their ain proprietary syntax and functions, which are not common other systems.

Therefore information technology is crucial that in order for a smooth transition from one organisation to some other you lot follow the SQL standards and only use commonly institute functions. To exemplify this in that location is a function normally used in queries: we can look at the function for randomisation in SQL. Here are the function specifications for various languages:

MySQL: SELECT RAND([seed]);
MS SQL: SELECT RAND([seed]);
PostgreSQL: SELECT RANDOM(); (to set the seed you must run SETSEED([seed])
beforehand)
Oracle DB: SELECT dbms_random.random FROM dual;
SQLite: SELECT RANDOM();

So we must go on this in mind, and work out whether we can either apply a standardised SQL technique instead of the proprietary function, or use a PHP procedure and inject the result into the SQL query (in the randomisation example we could employ the rand() function which PHP provides).

The gedit app on Linux is one of the fastest ways to modify code, and has syntax highlighting for many languages. It uses the Doctrine ORM system

The gedit app on Linux is one of the fastest ways to modify code, and has syntax highlighting for many languages. Information technology uses the Doctrine ORM system

xi. Object relational mapping by example

Of course, we can become further in abstraction by entering into the modelling world – no, non by exhibiting our projection on a catwalk, only via mapping Plain Erstwhile PHP Objects to database tables. There'south a trouble with this beacuse PHP objects take an object-oriented model, whereas SQL databases accept a relational one. This is where object relational mapping (ORM) comes into play: it enables you to map objects to tables, often using a bit of magic and some sparkle.

Yous're probably asking what the do good of ORM is. Quite simply, you don't have to deal with any of the database connectivity or SQL querying; y'all simply use PHP objects and their methods directly, and the ORM system deals with all the connectivity and the create-read-update-delete transactions in the groundwork. At that place are quite a few ORM libraries for PHP out there, PdoMap, Propel and Redbean being a few of the good ones, but the best I've used is Doctrine 2 – information technology has the do good of existence either usable on its own or every bit part of an MVC setup such every bit Symfony, CodeIgniter or Zend.

With Doctrine 2, and a few other ORM systems, ordinarily y'all define a set of objects and the kind of relationships that they have with each other (such every bit one-to-many; many-to-one; many-to-many), with special details nearly the connexion between backdrop and the methods. Of class, there's no need to ascertain normalised link tables because these are irrelevant in the object model. This human being-executed process is commonly washed using custom syntax, for instance in XML or YAML, and Doctrine ii allows for object relational definitions within PHP doc-blocks. The post-obit model and code describes a real-globe example.

<?php
utilize Doctrine\Common\Collections\ArrayCollection;
/** Description of Fellow member
* @Entity
*/
class Fellow member {
/**
* @Id @GeneratedValue
* @Column(type="integer")
* @var int
*/
protected $id;
/** @Column(type="string")
* @var string
*/
protected $firstname;
/** @Column(type="cord")
* @var string
*/
protected $surname;
/** @Column(type="string")
* @var string
*/
protected $electronic mail;
/** Many members have a membership of many groups
* @ManyToMany(targetEntity="Group")
* @var Grouping[]
**/
protected $groups;
/**
* Constructor
*/
public function __construct() {
$this->groups = new ArrayCollection();
// ...
}
// --- Basic getter and setter examples --- //
/** Gets the (internal) ID of the fellow member
* @return int
*/
public function getId() {
return $this->id;
}
/** Gets the Firstname of the member
* @return string
*/
public office getFirstname() {
return $this->firstname;
}
/** Sets the firstname of the fellow member
* @param string $firstname
*/
public function setFirstname($firstname) {
$this->firstname = $firstname;
}
// --- More complex getter and setter examples --- //
/** Gets the groups array of the member
* @return Group[]
*/
public function getGroups() {
return $this->groups;
}
/** Assigns a group to a fellow member
* @param Group $group
*/
public function assignToGroup(Group $grouping) {
$this->groups[] = $group;
}
/** Removes a fellow member from a group
* @param Grouping $group
*/
public part removeFromGroups(Group $group) {
$this->getGroups()->removeElement($group);
}
// ...
}
?>

A machine-executed process can then generate the SQL to create a database (this tin be in a variety of SQL syntaxes, such as for MySQL, for SQL Server or for PostgreSQL); information technology can practise this by dumping the SQL, or by connecting with the database and executing it itself. It will create the many-to-many link tables itself.

doctrine orm:schema-tool:create

or

doctrine orm:schema-tool:create --dump-sql

You will discover you've now got the PHP objects and the tables in place. Now you can deal with the objects without needing to know either how to connect with the database management system, or the structure of the relational tables.

$group = new Group();
// set grouping details, persist and flush (as beneath)
$member = new Fellow member();
$fellow member->setFirstname("");
$member->setSurname("");
$member->setEmail("");
$member->assignToGroup($group);
$entityManager->persist($member);
$entityManager->affluent();
echo "Created Member with ID " . $member->getId() . "\due north";

Of form at that place's a flake more than to it than the code examples above, primarily regarding connection details and bootstrapping, but I thought that I should give y'all a flavour of the ability of ORM and Doctrine in particular. I should add that Doctrine two, and a couple of the other PHP ORM libraries, use PDO in club to attain support for diverse dissimilar RDBMSes.

Usefully, the Doctrine system includes extensive in-built assistance whenever you need it

Usefully, the Doctrine arrangement includes extensive in-congenital assistance whenever yous need it

12. Conclusion

I have used PDO in commercial projects, and from my ain experience it greatly increases the ease of connecting to a database – and dealing with the information afterward – thanks to its object-orientation. There's no need to use PDO but for its organization switching adequacy; the functions are there for yous to employ, accept practiced efficiency and are ideal for contemporary programming design patterns.

At that place are many systems out in that location still using the procedural-way systemspecific functions, but I certainly have seen a shift in focus to PDO. We tin besides come across PDO in action in the wild, because Drupal, MediaWiki, WordPress and many other popular open up source web applications at present fully or partially support the PDO organization for connecting to databases. I have a vision in which data is no longer closely-coupled with databases, and databases are no longer closelycoupled with code, and we see more general purpose systems being configured to specific applications. I think that ORM systems, NoSQL and linked data are three things to look out for in the present and in the futurity. The killer features of future spider web applications will, firstly, have the foundations of the connectivity of data, and secondly, by the efficiency of the manipulation of that data.

Detect 101 CSS and Javascript tutorials.

Daniel Lewis is a web app developer, consultant, tutor and speaker.

Related articles

wernerboremat.blogspot.com

Source: https://www.creativebloq.com/design/using-php-data-objects-1133026

0 Response to "Joomla Failed to Read Session Data Native.php"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel