Sorry about this question but i never worked with SQLite, and i gone through the SQLite site , downloaded "Precompiled Binaries For Windows" files tried to make them usable for my purpose but i couldnot, i saw with working tutorials with databases,tables.
My tasks is to get data from SQLite and put them into magento mysql DB. So for that i have got the SQLite DB dump file as .db3 file, txt file which has size of db dump file(20110125_SIZE).
So how can i import it into the SQLite. Please if anyone of you worked with SQLite3 help me to understand the .db3 file and how can i see the records from them.
I have got sqlite3 db dump as dbname.db3,
So then i tried to connect this sqllite from php. Here is my sample code which i got it from forum.
$db = openDatabase();
unset($db);
function openDatabase() {
$dbFile = realpath('dbname.db3');
echo $dbFile . "\n";
$needDbCreate = !file_exists($dbFile);
$db = new SQLiteDatabase($dbFile) or die((file_exists($dbFile)) ? "Unable to open" : "Unable to create");
if($needDbCreate) {
}
return $db;
}
But i am getting fatal exception.
Fatal error: Uncaught exception
'SQLiteException' with message
'SQLiteDatabase::_construct() [sqlitedatabase.--construct]:
file is encrypted or is not a
database' in
C:\wamp\www\SQLITE\index.php:23 Stack
trace: #0
C:\wamp\www\SQLITE\index.php(23):
SQLiteDatabase->_construct('C:\wamp\www\SQL...')
1 C:\wamp\www\SQLITE\index.php(15): openDatabase() #2 {main} thrown in
C:\wamp\www\SQLITE\index.php on line
23
But when i tried the same sqldump with the PDO , i got connected.
try {
$dbh = new PDO("sqlite:C:\wamp\www\SQLITE\dbname.db3");
echo 'Db Connected <br/>';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
here i do not know the list of tables available in this dump so how can i query them to list and then getting records from them.
Please help me to solve this issue ti get connected and browse the tables from php.
Sorry for posting here in answer
section, i wanted to highlight the
code.
Thanks
On a system where SQLite is installed, you will usually also have the sqlite3 command line program. It can be used both from the command line or in interactive mode to dump data or load it into a (binary) database file.
sqlite3 ./database.file
This will give you the interactive prompt, where you can issue SQL commands or special commands such as .help or .dump.
There are also more graphical tools, but they are probably overkill for what you want to do.
Edit: seeing your reply (currently in the answer section), it seems that your .db3 file simply is not in the binary SQLite3 format, but instead perhaps a dump. That would be a problem. If it is a dump, you'd have to load it into a proper database file first.
cat yourdump.sql|sqlite3 ./realdb.db3
call three times
$rr=exec("sqlite3 database.db \".separator '|'\" ");
$rr=exec("sqlite3 database.db \".import myfile.txt tablename\" ");
$rr= exec ("sqlite3 database.db \"pragma encoding = 'utf-8'\" ");
or
single line
$rr=exec("sqlite3 database.db \".separator '|'\" && sqlite3 database.db \"pragma encoding = 'utf-8'\" && sqlite3 database.db \".import myfile.txt tablename\" ");
Related
This is first post of a question. Tried to find an answer here, but all relevant posts seems dated or use deprecated mysql.
New to sqlite, so forgive what might appear stupid, but the query in the code below never works. Note: we are running sqlite3 and PDO on site with php 5.6.
A Program to create the db worked fine. And the app "Db Browser for SQL Lite" shows DB and tables and data just fine. But this:
<?php
//open the database
$myPDO = new PDO('sqlite:MySqlitedb1');
print "<p>db opened</p>";
$result = $myPDO->query('SELECT * FROM users');
//if the query works
if ($result !== FALSE) {
print "<p>query ran</p>";
foreach($result as $row){
print "<p>".$row."</p>";
}
} else {
// when the query fails
print "<p>query failed</p>";
} //end if
// close the database connection
$myPDO = NULL;
?>
Always results in a 'query failed'. Queries for specific records that ARE there also fails.
Also Tried some other testing in code above using fetch and fetchall, and they generated errors like:
mod_fcgid: stderr: PHP Fatal error: Call to a member function fetchAll()
on boolean in (path emoved)/testpdo2.php on line 27
Which I am sure was caused by the fact the query fails so $result is null/false
I am obviously missing something stupid here?
Joe C.
This is solved. The code should have worked (it does now). It was not
a directory issue
a permissions issue
a debug_kit.sqlite file in the tmp directory, or any files in the tmp dir.
a SCP or 'sync' directory issue
I altered the code and trapped an exception (1st with 'bad' DB then good one):
<?php
$myPDO = NULL; //close db just in case...
//open the database
$myPDO = new PDO('sqlite:newsqlite2.db');
//throw exceptions
$myPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($myPDO != null)
print "<p>db connected</p>";
else
print "<p>db did not connect</p>";
// result: db does open
//1st test
try
{
$result0=$myPDO->query('SELECT * from users');
print "<p>query ran</p>";
}
catch(PDOException $e)
{
echo "Statement failed: " . $e->getMessage();
return false;
}
// close the database connection
$myPDO = NULL;
?>
This threw an error with the original DB (MySqlitedb1) and an PDO exception:
SQLSTATE[HY000]: General error: 11 database disk image is malformed
Now, DESPITE analyse tools run on the database saying it was 'fine' and being able to work on the database with tools like "DB Browser for SQLite" without ANY issues, nor having issues creating other DB's, SOMETHING was amiss with the file. This caused the query's to fail and always return as a Boolean 'false', so the code failed.
We fixed the DB by dumping it to a sql file, then importing it (with "DB Browser for SQLite") to create a new database (newsqlite2.db), with the data. Using that DB, the code ran fine, extracted data etc.
As to why/how the database became "corrupt" or what the weird corruption was, I have not a clue. :)
Joe C.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to learn how to use PHP PDO as Object Oriented Programming.
I have tried following these two tutorials:
http://culttt.com/2012/10/01/roll-your-own-pdo-php-class/
http://culttt.com/2012/09/24/prevent-php-sql-injection-with-pdo-prepared-statements/
but I can't get anything on either of them to work.
The second one gives a download link to a pre-written wrapper class class.db.php from http://www.imavex.com/php-pdo-wrapper-class/
using this pre-written wrapper class and trying something as simple as this tutorial.php (credentials changed):
// Include the database class
include("class.db.php");
// Connect to database
$db = new db("mysql:host=localhost;dbname=my-db-name", "my-username", "my-password");
$results = $db->select("ad_publication");
print_r($results);
The above shows a blank page.
I know there is nothing wrong with the pre-written class and the text of the above example as it was copied directly out of the tutorial and the comments are full of thanks and praise.
I know there is nothign wrong with my credentials as this works fine:
try
{
$pdo = new PDO('mysql:host=localhost;dbname=my-db-name', 'my-username', 'my-password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
$output = 'Connection Successful';
echo $output;
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server.' . $e->getMessage();
echo $output;
exit();
}
And outputs Connection Successful
My Server is running PHP 5.5 and the table used in the example above is an InnoDB table.
When I run the example select statement my error logs show:
PHP Notice: Undefined variable: GhG678 in /var/www/vhosts/mywebsite.com.au/httpdocs/booking/tutorial.php on line 7
line 7:
$db = new db("mysql:host=localhost;dbname=my-db-name", "my-username", "my-password");
PHP Warning: Creating default object from empty value in /var/www/vhosts/mywebsite.com.au/httpdocs/booking/class.db.php on line 18
line 18:
$this->error = $e->getMessage(); // (from public function __construct)`
PHP Fatal error: Call to a member function select() on a non-object in /var/www/vhosts/mywebsite.com.au/httpdocs/booking/tutorial.php on line 9
line 9:
$results = $db->select("ad_publication"); // (an existing table with data in it)
I just can't see what I could be doing wrong especially as the wrapper class was not written by me and no-one else is complaining about it (heaps of praise) and the contents of tutorial.php were copied directly from the page with only the table name changed.
Like I say, using the PDO connection and doing normal PDO queries without the wrapper class, work fine.
Can anyone here see anything that could be going wrong or know of anything that I should look at?
I'm not sure why I copped a -1 for that question??
I thought it was very complete.
Anyway, thanks to #Sean for providing the clue to the answer.
My password does in fact have a $ character in it.
The connection code of mine that does work (as shown above) is:
$pdo = new PDO('mysql:host=localhost;dbname=my-db-name', 'my-username', 'my-password');
Their code that I was using is:
$pdo = new PDO("mysql:host=localhost;dbname=my-db-name", "my-username", "my-password");
changing the " characters to ' worked straight away.
The password was auto-generated by my hosts (Plesk) and I don't know enough about PHP to know that there is a difference between ' and ". I've never known why some people use one and some use the other. Seems I still have a lot to learn.
#Sean, because you didn't put it as a reply, I couldn't choose your suggestions as the answer, so I don't know how to give you the points, but thank you very much for steering me in the right direction.
I am trying to get my fist sqlite programs with php working on localhost but I can't get it to work. On my machine I have installed Sqlite3 and all works fine with C/C++.
If I move created database to localhost, give read/write permissions to db file and try to access them through php I get following error message:
file is encrypted or is not a database
Here is example code I use:
<?php
$dbhandle = sqlite_open("m_test1.db", 0666, $error);
if (!$dbhandle) die ($error);
$stm = "CREATE TABLE Friends(Id integer PRIMARY KEY," .
"Name text UNIQUE NOT NULL, Sex text CHECK(Sex IN ('M', 'F')))";
$ok = sqlite_exec($dbhandle, $stm, $error);
if (!$ok)
die("Cannot execute query. $error");
echo "Database Friends created successfully";
sqlite_close($dbhandle);
?>
If I run this code through browser when database don't exists then I get:
unable to open database: /var/www/m_test1.db
Info:
sqlite_libversion: 2.8.17
phpversion: 5.3.2-1ubuntu4.14
linux Ubuntu 10.04
By looking to phpinfo it seems that SQLite, SQLite3 and PDO_Sqlite is enabled.
Any help to get this working will be appreciated.
EDIT:
Solution is: 'chmod ugo+rwx /var/www' :)
After that sqlite_open and PDO both can create database.
PHP5 doesn't play nice with sqlite_open(). You'll need to use a PDO instead, like shown here: https://stackoverflow.com/a/4751965/369032
(code copied from above answer)
try
{
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:VPN0.sqlite");
echo "Handle has been created ...... <br><br>";
}
catch(PDOException $e)
{
echo $e->getMessage();
echo "<br><br>Database -- NOT -- loaded successfully .. ";
die( "<br><br>Query Closed !!! $error");
}
echo "Database loaded successfully ....";
I am new to Joomla and new to php (wish I was so new in age too). I have installed joomla on a local apache webserver. I am trying to use some php code in a joomla article in order to fetch some data from a Sybase ASE 12.5 database. I installed sourcerer and started to try an ODBC connection using a system DSN (which I verified it is working):
{source}
<?php
echo 'This text is placed through <b>PHP</b>!';
echo '<p>';
echo '</p>';
$conn = odbc_connect('myDSN', 'sa', 'myPassword') or die('Could not connect !');
echo 'Connected successfully';
$sql = 'SELECT day, name FROM my_table where month = 1';
odbc_close($conn);
?>
{/source}
The above code doesn't do much, but this is how far I can get without problems. I refresh the joomla page and I see inside the article's text:
...
This text is placed through PHP!
Connected successfully
...
Seems ok, the connection obviously established (I verified this by stopping the sybase service and getting the "Could not connect" message). Then I added one more line, just below the $sql assignment.
$rs = odbc_exec($conn,$sql);
I refresh and ...I see nothing coming from the script (not even the "This text is placed through PHP!").
Obviously, I see nothing if I include code to echo the contents of $rs. I also tried this but in vain.
if (!$rs)
{exit("Error in SQL");}
Once I add the odbc_exec command, the entire script ceases working.
In php.ini I read:
; Windows Extensions
; Note that ODBC support is built in, so no dll is needed for it.
Do you have any idea what is going wrong?
UPDATE
Connecting to a MySQL database using code like this, works like a charm.
To answer your question
Is this the correct way to get data
from another database in to an article
or should I use some plug-in to do
that?
The correct way is to use JDatabase object which you get by JFactory::getDBO() or JDatabase::getInstance(), see Joomla JDatabase documentation.
$db = JDatabase::getInstance( $databasConfigArray );
$db->setQuery('your query');
$data = $db->loadObjectList();
Here is a good tutorial showing how to connect to multiple databases in Joomla, there is even source code for helper class.
Also look at this thread Connecting to 3rd party databse in Joomla!?
I have a written a script in PHP that reads from data from a MySQL database. I am new to PHP and I have been using the PDO library. I have been developing on a Windows machine using the WAMP Server 2 and all has been working well. However, when I uploaded my script to the LINUX server where it will be used I get the following error when I run my script.
Fatal error: Call to undefined function query()
This is the line where the error is occuring ...
foreach($dbconn->query($sql) as $row)
The variable $dbconn is first defined in my dblogin.php include file which I am listing below.
<?php
// Login info for the database
$db_hostname = 'localhost';
$db_database = 'MY_DATABASE_NAME';
$db_username = 'MY_DATABASE_USER';
$db_password = 'MY_DATABASE_PASSWORD';
$dsn = 'mysql:host=' . $db_hostname . ';dbname=' . $db_database . ';';
try
{
$dbconn = new PDO($dsn, $db_username, $db_password);
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Error connecting to database: ' . $e->getMessage();
}
?>
Inside the function where the error occurs I have the database connection defined as a superglobal as such ...
global $dbconn;
I am a bit confused as to what is happening since all worked well on my development machine. I was wondering if the PDO library was installed but from what I thought it was installed by default as part of PHP v5.
The script is running on an Ubuntu (5.0.51a-3ubuntu5.4) machine and the PHP version is 5.2.4. Thank you for any suggestions. I am really lost on this.
Always, but always, develop on the same platform as your production platform. Try your best to mirror the versions of server software (PHP, MySQL, etc). There will always be differences between installs, and especially in the way different OS platforms handle things. Use the old 'phpinfo()' script on each server to compare the differences, if any.
At any rate, even if both the Win and Linux platforms here have the exact same versions of everything, have you checked your configuration? In other words, is the MySQL host name in your DSN a local MySQL host (linked to your Win development platform), or the actual host the Ubuntu server uses? Or are they both "localhost" in either case? Double check this. Also, have you mirrored all data on both servers?
Do you know for a fact that the Ubuntu server has PDO? You essentially said you assume they are the same. Don't assume, verify.
As sobedai mentioned, look at the output of var_dump($dbconn), check that it is actually a PDO object, and go from there.
This is a typical PDO deployment for me:
// 'logger' is a custom error logging function with email alerts
try {
$dbh= new PDO(dsn);
if ( is_a($dbh, "PDO") ) {
$sql= 'SELECT field FROM table';
$stmt= $dbh->query($sql);
if ( is_a($stmt, "PDOStatement") ) {
// handle resultset
}
else {
// weirdness, log it
logger("Error with statement: {$sql}" .$dbh->errorCode());
}
}
else {
// some weirdness, log it
logger('Error making connection: '. $dbh->errorCode());
}
}
catch (PDOException $e) {
logger('PDOException caught in '.__FILE__.' : '. $e->getMessage());
}
catch (Exception $e) {
logger('General Exception caught in '.__FILE__.' : '. $e->getMessage());
}
Note I'm using PDO::errorCode in there, referencing the SQL-92 state codes.
Also, refer to the manual as much as possible.
Generally when this happens, the object you're trying to reference is not actually an instance of a class.
Since you've been developing on WAMP and testing on LAMP, include paths immediately come to mind.
Check the php includes path is correct on your LAMP stack.
Check that all the necessary libs are installed (just do a quick phpinfo() page or you can use php -i from the command line).
And last but not least - do:
echo var_dump($dbconn);
confirm that it is indeed the object you think it is.