Connect to localhost sqlite db with php - php

I have UwAmp installed and running. I have set up a mysqlite db on the localhost and I'm trying to connect to it using the following PHP code:
<?php
try
{
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:graspe.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 ....";
?>
The db is called graspe and when I run this script it says that it has connected successfully. If I change the name of the database to something else it still returns a successfully connected message. What am I doing wrong? Thanks in advance.

By default when you construct a new connection to sqlite database - that database will be created if it doesn't exists.
If you want to test your code to make sure it throws an exception when the database cannot be created you can try to write to filename that you don't have permissions to (new PDO("sqlite:/");)

Related

Problems opening a SQLITE database from PHP and reporting outcomes to the HTML page

I am new to PHP.
I need to open a database and delete an entry, however I don't want to create a new db if it doesn't exist. If it doesn't exist, I'd like to return an error to the HTML page from which the query originated.
Problem is that neither
echo "Unable to open database\n";
nor
echo "entry deleted\n";
nor the
alert("entry deleted");
show on the browser's console or on the webpage despite the fact that the entry is successfully deleted. I am using Safari on Mac. HTML page logs appear on the console but PHP pages logs don't. Also the alert does not pop up if invoked from the PHP page.
I want to have full control of the success / no success of the operation, so that this info can be fed back to the HTML page and other methods can be triggered accordingly.
Any help would be appreciated! Thanks
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('myDb.db');
}
}
$db = new MyDB();
if(!$db)
{
echo "Database does not exist";
} else {
echo "Opened database successfully\n";
//Do something (delete entry)
echo "entry deleted\n";
alert("entry deleted");
}
?>
$db will always be an instance of MyDB class, it can't really be evaluated in a if because it will always be truthy. So the code echo "Database does not exist"; won't ever run.
Also, php doesn't output to the browser console. And there's no alert function built-in in php (but not sure if you have that defined somewhere else).
From the docs, SQLite3::open doesn't return anything, and it doesn't state if it throws an exception if can't open the database. The docs says that SQLite3::__construct throws an exception if it can't connect, so you should stick to that (and don't use the class MyDB example from SQLite3::open).
try {
$db = new SQLite3();
echo "Opened database successfully\n";
//Do something (delete entry)
echo "entry deleted\n";
} catch (\Exception $e) {
// database does not exists
...
}
Would need to check your `//Do something (delete entry)` code to be sure that it's not returning earlier.

Simple Query using sqlite 3, php and PDO fails

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.

How to connect to sql database through php/pdo that has been exported from mysql/phpmyadmin as mydatabase.sql?

I have searched on many different sites and cannot find an answer that specifically answers this question:
I have WAMP Server installed, which installed phpmyadmin as well as MySQL. I can easily connect to the database through php/pdo by using localhost as my hostname.
But my problem is I am trying to connect to a database that I have exported from phpmyadmin as "mydatabase.sql". So now lets say I placed this file on my pc at "C:\Users\Username\Desktop\MyFolder\mydatabase.sql". How would I connect to this database (if this is possible)?
The reason is that I cannot install WAMP Server on all the pcs that would use this program. so would like to be able to connect to the database without having to install any type of servers, etc...
My php at the moment is:
<?php
$dsn='mysql:C:\Users\Username\Desktop\MyFolder\mydatabase.sql';
$username='username';
$password='pass';
try
{
$dbh = new PDO("$dsn",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to Database<br/>';
$sql = "SELECT * FROM users";
foreach ($dbh->query($sql) as $row)
{
echo $row["ID"] ." - ". $row["Name"] ."<br/>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Also, if this is possible, would username and password be necessary to connect to an "off server database"?
If I try:
$dsn='sqlite:C:\Users\Optique\Desktop\optique.sql';
I get:
"Connected to Database
SQLSTATE[HY000]: General error: 26 file is encrypted or is not a database"
But I think that is because SQLite uses a different database format than MySQL (stand to be corrected). So what I need is something similar to the SQLite driver for MySQL.
Thanks in advance!
You cannot find an answer simply because it doesn't exist: it's impossible to connect to an SQL dump through PDO, and it makes no sense anyway: a dump is not a database but simply a collection of INSERT queries. Unlike sqlite, for mysql you need a server to connect with.
To be able to connect, you should import that dump into mysql database first and then connect to that database with PDO.

Can't log to oracle local DB using PHP with WebMatrix- shows an empty page

I've been trying to use the following code to connect to the oracle db from WebMatrix:
<?php
// Create connection to Oracle
$conn = oci_connect("sys","password","//localhost:1521/xe");
if (!$conn) {
$m = oci_error();
echo $m['message'], "\n";
exit;
}
else {
print "Connected to Oracle!";
}
// Close the Oracle connection
oci_close($conn);
?>
For some reason, it just shows an empty page in the browser (Chrome).
Any other thing I'm trying to program using php (like echo hello world and such) are working.
What's weird that I don't even see a message of failure or success.
I'm using windows 7 64bit.
Got any idea what might be the problem ? (I've searched all over and tried many things before asking here).

SQLite on localhost with php doesn't work (Linux)

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 ....";

Categories