Solved

pdo connecting to text file

Posted on 2014-01-06
9
849 Views
Last Modified: 2014-01-14
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
0
Comment
Question by:rgb192
9 Comments
 
LVL 13

Accepted Solution

by:
Phil Phillips earned 84 total points
ID: 39760134
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
0
 
LVL 34

Assisted Solution

by:gr8gonzo
gr8gonzo earned 250 total points
ID: 39760135
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.
0
 

Author Comment

by:rgb192
ID: 39761298
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.
0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 83 total points
ID: 39761872
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
0
 
LVL 34

Assisted Solution

by:gr8gonzo
gr8gonzo earned 250 total points
ID: 39762209
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.
0
 
LVL 34

Assisted Solution

by:gr8gonzo
gr8gonzo earned 250 total points
ID: 39762272
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.
0
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 83 total points
ID: 39763331
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.
0
 

Author Closing Comment

by:rgb192
ID: 39780919
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.
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
form builder not starting 3 37
php simple error message 4 23
What does $selected = $month == $beginning_month ? 'selected' : ''; mean? 5 30
Mongo DB 18 46
Read about achieving the basic levels of HRIS security in the workplace.
As technology users and professionals, we’re always learning. Our universal interest in advancing our knowledge of the trade is unmatched by most industries. It’s a curiosity that makes sense, given the climate of change. Within that, there lies a…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question