pdo connecting to text file

does pdo connect to a text file

I have a website that is not connecting to our ip address mysql and I think it would be easier to prepare a flat file rather than try to configure mysql
LVL 1
rgb192Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Phil PhillipsDevOps ArchitectCommented:
You can use a flat file database.  Try taking a look at SQLite (http://www.sqlite.org).  I would only recommend it for a low-traffic site, or something internal though (See: http://www.sqlite.org/whentouse.html)


SQLite PDO Docs: http://us3.php.net/manual/en/ref.pdo-sqlite.php

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gr8gonzoConsultantCommented:
No, not really, but that's a good thing. Text files aren't meant to be used as data sources. They get locked and can prevent multiple users from accessing the data at the same time. You can use SQLite (there is a PDO driver for that), which is a flat file type of database which gives you SQL-like behavior (tables, SQL querying, etc...) without needing a separate server for it.
rgb192Author Commented:
But you are telling me to connect to sqlite

this server will not let me connect to my open mysql connection

so now on this server I have to learn how to install sqlite?

And yes, only need one user at a time.
Is there an easier solution.
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Ray PaseurCommented:
Run phpinfo() and look in the output for "PDO" to see if you already have sqlite installed.

Here is a sample script to help you get started.

<?php // pdo_error_example.php

// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28331641.html#a39761872
// MAN PAGE: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

ini_set('display_errors', TRUE);
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');
echo '<pre>';


// SET UP OUR PHP DATA OBJECT USING SQLITE
$db_name = 'SqLite.db';
$db_drvr = 'sqlite';
try
{
    $pdo = new PDO("$db_drvr:$db_name");
}
catch(PDOException $e)
{
    var_dump($e);

}

// SET PDO TO TELL US ABOUT WARNINGS OR TO THROW EXCEPTIONS
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

echo "PDO OBJECT: ";
var_dump($pdo);
echo PHP_EOL;


// PREPARE THE QUERY -- THIS IS THE RIGHT WAY, WITH NAMED PLACEHOLDERS
$sql
=
"
INSERT INTO gooseball
(  symbol,  price,  xtime ) VALUES
( :symbol, :price, :xtime )
"
;

// THIS PREPARES THE QUERY (FAILS FOR NO SUCH TABLE NAME)
try
{
    $res = $pdo->prepare($sql);
}
catch(PDOException $e)
{
    var_dump($e);
}

Open in new window

HTH, ~Ray
gr8gonzoConsultantCommented:
sqlite isn't a server that you have to install. It's a type of database that simply requires a driver (like the PDO one). The driver has all the instructions on how to build a new SQLite database and work with it, so as Ray was saying, if you have the SQLite PDO driver installed, then you don't need to do anything more than use it.

That said, I'm not usually a fan of SQLite. It's nice if you don't want to run a full server, but if you need the features of a database, then in most cases, the extra effort it takes to set up MySQL (or any other database server) is usually worth it in the long run. SQLite is best used in situations where you -can't- run a server (e.g. low-memory situations, or working within security restrictions). It's sort of like Microsoft Access, if you're familiar with that.

I would never recommend trying to use a flat text file for a data backend unless you will be the only user of the application. Done incorrectly, you can easily end up corrupting a text file if multiple users try to write to it at the same time without locking.
gr8gonzoConsultantCommented:
And yes, only need one user at a time.
I just noticed that quote. One thing I have done in the past is simply use JSON or serialization to store and retrieve data, like a mini-database:

<?php

$PA = new PersistentArray("smithfamily.json");

// Add data if there is none
if(!count($PA->data))
{
	echo "Adding three members to the Smith family!\n";
	$PA->data[] = array("name" => "John Smith", "dob" => "01/01/1980");
	$PA->data[] = array("name" => "Mary Smith", "dob" => "01/01/1983");
	$PA->data[] = array("name" => "Baby Smith", "dob" => "01/01/2005");

	// Save data
	$PA->save();
}
else
{
	// We have data already
	echo "Loading up the existing Smith family!\n";
	print_r($PA->data);
}

class PersistentArray
{
	// Our data
	public $data = array();
	private $file = "";
	
	// Constructor
	public function __construct($file)
	{
		$this->file = $file;
		$this->load();
	}
	
	public function load()
	{
		if(file_exists($this->file))
		{
			$this->data = json_decode(file_get_contents($this->file),true);
		}
	}
	
	public function save()
	{
		file_put_contents($this->file,json_encode($this->data),LOCK_EX);
	}
}
?>

Open in new window


Again, it's not perfect, but in a pinch it might be what you're looking for if you don't need all the features of a database and just need the persistence of data (no melting CDs or Salvador Dali required).

The downsides are:

1. ALL of the data is loaded into memory. So if you have a large dataset, then you might run into memory problems (a database server will help with this).

2. You're simply working with an array, so you are limited to what you can normally do with an array (no SQL searches, for example).

3. You have to load the data into the array first, so if the data is in a CSV, you'll need to convert it to the array first.
Slick812Commented:
greetings  rgb192, , I read your comments here, but you do not say or give us INFO about what and how much data-info ( like how many users, 25, 50, 500, or thousands of users, makes a difference for File based storage)
I will guess that since there is NO MySQL installed, this is a very LOW hit rate server, with just light traffic?
I have used the SQLite to good effect, it is almost always installed with PHP, and usually with PDO, although I have had problems on different servers with having SQLite version 2, or SQLite version 3. The current newer SQLite version 3 can do very much web traffic without bogging down or slowing much, but It will not handle  high throughput SQL as well as MySQL.

If you want a to ONLY select a single user from a disk File storage you might try this code -
<?php
// first make your USERS ARRAY
$users = array(); // array holds arrays of user data ID, email, url
$users['_ID_S'] = array(); // ID INDEX array, you can NOT have any Users Named '_ID_S'
for ($i=1; $i < 7; ++$i) { // make 6 experimental Users 'uName1' to 'uName6'
$ur = 'uName'.$i;
$users[$ur] = array('ID'=>120+$i, 'email'=> 'uName'.$i.'@mailer.com', 'url'=> 'www.web'.$i.'.net');
$users['_ID_S'][$users[$ur]['ID'] ] = $ur;// put User name in ID INDEX array
}
file_put_contents('users_FDB', serialize($users));

// ATTENTION the above is just to show you ONE WAY to make a DATA FILE


class userDataFile {
public $aryUsers = array();
	
public function __construct($file){
if (file_exists($file)) {
  $this->aryUsers = file_get_contents($file);
// Get ARRAYS by unserialize( )
  $this->aryUsers = unserialize($this->aryUsers);
  } 
  else // warning be sure to set something as dedault, if the is NO FILE
  {$this->aryUsers['_ID_S'][120] = 'user1';
  $this->aryUsers['user1'] = array('ID'=>120, 'email'=>'ur1@mail.com', 'url'=>'www.web.net');
  }
}

public function User_by_Name($uName) {
return $this->aryUsers[$uName];
// returns ARRAY, or null if there is NO array for user name
}

public function User_by_ID($ID) {
// This will use an ID INDEX array to fild the User name
if (isset($this->aryUsers['_ID_S'][$ID])) {
  $usr = $this->aryUsers['_ID_S'][$ID];
  $ary = $this->aryUsers[$usr];
  $ary['uName']= $usr; // you must ADD the name to array
  return $ary;
  } else return null;// if NO ID give out a null
}
} // end of class userDataFile
	
//  //  // // /// //   //  //
	
$userDF = new userDataFile('users_FDB');

$ur = 'uName1';
$aryUser = $userDF->User_by_Name($ur);
echo 'Data from User_by_Name() for '.$ur.', ID= '.$aryUser['ID'].', email= '.$aryUser['email'].', url= '.$aryUser['url'].'<br />';

$id = 123;
$aryUser = $userDF->User_by_ID($id);
echo 'Data from User_by_ID() for '.$id.', uName= '.$aryUser['uName'].', email= '.$aryUser['email'].', url= '.$aryUser['url'].'<br />';
echo '<br />Here are All Users -<br>';
foreach($userDF->aryUsers as $name => $ary) {
  if ($name == '_ID_S') continue;
  echo 'Data user= '.$name.', ID= '.$ary['ID'].', email= '.$aryUser['email'].', url= '.$aryUser['url'].'<br />';
  }
?>

Open in new window

File based data storage can be very usefull, and can function really well, if there is not continuous writes to that file, but even if you write to data files, the modern server  systems can do tremendous  file operations with only slight delays, IF the file is less than 8 kilobytes,  but if your data files get above 50 Kb or 75 kiloBytes, then for high file write traffic, there may be some difference in performance.
Ask questions if you need more info.
rgb192Author Commented:
So flat file has memory issues and sqlite is recommended by many experts and json. So I will go with sqlite because it is built into php.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.