Cannot access SQLite3 db using php - php

I've spent many-a hour trying to get a local webserver working (I'm new)
I created a sqlite3 database ('database.sql') in the www folder, and tried calling it with numerous different php commands (php 5.5, I checked) such as '$test = new SQLite('database.sql')' or the same with SQLite3, both with no luck. Also tried $test->open('database.sql').
Always with the fatal error "Class 'SQLite' not found". I've spent too many hours on what I'm sure is a very simple problem, I'm sorry to have to ask this!

To open a DB using PHP5 and SQLite we need to use a PDO and not the sqlite_open() function.
This is how to open or create a database: (not sure if it's bug free)
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:VPN0.sqlite");
echo "Handle has been created ...... <br>";
}
catch(PDOException $e) {
echo $e->getMessage();
echo "<br>Database is loaded UNSUCCESSFULLY .. ";
die("<br>Query is closed $error");
}
echo "Database loaded SUCCESSFULLY ....";
Hope this helps!

There is a php package called sqlite3 which you can use (as well as PDO which is given above). Here is a fraction of code which uses it.
$db = new SQLite3(DATABASE);
if (isset($dbversion)) { //only newer versions of chat will have this
$version = $db->querySingle("SELECT value FROM parameters WHERE name = 'db_version'");
Where the DATABASE variable has been defined with
define('DATA_DIR',$datadir); //Should be outside of web space
define('DATABASE',DATA_DIR.'chat.db');

Are you sure that the package is installed on your server?
If you're still having problems you can do a couple of things. First, use phpinfo(); in a page to determine if the SQLite3 extension is installed.
Second, if you want to use PDO make sure that the following line in your php.ini is un-commented:
extension=php_pdo_sqlite.dll
If you have to un-comment this you will need to restart your server for the changes to take effect.

Related

Installing drivers for SQL Server in PHP

I'm new to PHP. PHP is installed and working, and now I'm trying to set up connection with a SQL Server DB. Following instructions from a Youtube video. Went through and finished installing the drivers, but it isn't working. My test page stops running code after the sqlsrv_connect() function is called. I'm not even getting an error message. Below is my test page code:
<?php
echo '<br><span style="font-weight:bold;">PHP functioning. This line is being echoed out.</span><br />';
/*No problems yet...*/
$serverName = "Myserver";
$connectionInfo = array('Database'=>'nde', 'UID'=>'sa', 'PWD'=>'!hegEcu&3ATr');
$conn = sqlsrv_connect($serverName, $connectionInfo);
/*Nothing is appearing on the screen after this */
echo 'Still working...<br />';
if ($conn) {
echo 'Connection established.<br />';
} else {
echo 'Nope.<br />';
die(print_r(sqlserv_errors(), TRUE));
}
?>
I'm running PHP 7.0.21, and SQL Server 2014. I went and downloaded the two DLL files I think I need - php_pdo_sqlsrv_7_ts_x64.dll, and php_sqlsrv_7_ts_x64.dll. I copied them to Program Files/PHP/v7.0/ext. I went into PHP.ini as admin, and typed:
extension=php_pdo_sqlsrv_7_ts_x64.dll
extension=php_sqlsrv_7_ts_x64.dll
in the Windows Extensions sections. I saved PHP.ini, restarted both the IIS Admin Service and World Wide Web Publishing Service, and went into IIS Manager and restarted the server. PHP is still working, but I'm still not getting any echo after the sqlsrv_connect() call.
Okay, I got it working. As ctwheels suggested, i just installed the nts driver versions instead of the ts versions, which are php_pdo_sqlsrv_7_nts_x64.dll and
extension=php_sqlsrv_7_nts_x64.dll. It's working with sqlsrv_connect(); I haven't tried using PDO. I'm new to PHP and unfamiliar with PDO, but I'll probably come across it again, especially as I start looking into PHP frameworks (Cake and CodeIgniter).
One important thing to share for anyone who might also be new to PHP - the PHP documentation says that the $serverName argument of sqlsrv_connect() should be in the format of servername/instancename. So I used this query to get both: select ##servername + '\' + ##servicename, and got "Myserver\MSSQLServer". However, using this as the $serverName argument caused the connection to fail. Only after I took out "\MSSQLServer" did it connect successfully. So as in the code above, the correct value to use was $serverName = "Myserver".

How can I use PDO with MSSQL in PHP from a Windows dev envirenment?

I am developing an application that needs to get data from an outside MSSQL database. I spent a lot of time trying to get various methods of connection to MSSQL with PHP, but there were several routes which were depreciated.
On my production environment running Debian, I was able to make a connection with PDO_DLIB and FreeTDS with something like this:
$this->db = new \PDO('dblib:host='.$thedb_host_prod.';dbname='.$thedb_database_name_prod, $thedb_database_user, $thedb_database_pass);
On Windows, MSSQL is depreciated. I believe I'm using the Microsoft SQL Server Driver and was only able to get it to work with ODBC, which looks something like this:
$dsn = "Driver={SQL Server};Server=".$thedb_host_dev.";Database=".$thedb_database_name_dev;
$this->odbc = odbc_connect($dsn, $thedb_database_user, $thedb_database_pass);
Then, the problem becomes, in each method I need to do something differently for ODBC than I do for DLIB.
public function exampleMethod(){
// logic and create the query in $query
if($this->dev == false){
// PRODUCTION
try {
$stmt = $this->db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
} else {
// DEVELOPMENT
$query = $query;
$stmt = odbc_exec($this->odbc, ($query));
$result = array();
while($currentRow = odbc_fetch_object( $stmt )){
$jobNumber = $currentRow->Code; // Set object key to jobNumber
array_push($result, $currentRow);
}
}
}
This actually works, but the problem is, with how the query for ODBC needs to be prepared vs how the DBLIB query should be prepared, means that if I don't want to write the query twice in each method, I have to create it before each action. This is really bad because it means I'm not putting my variables into the query with PDO's bindValue.
So, has anyone been able to get PDO work with PHP 5.4 and MSSQL in a Windows environment? Does anyone see a way of securing the query in a way that doesn't make me duplicate the query in each method, once for ODBC and once for DBLIB?
My plan currently is to develop the application out and then remove all of the ODBC stuff which will allow me to put the query in the $stmt properly, avoiding this problem. But until then, it's making development a huge pain.
Oooook, so I finally got it working !
Here are the libraries / drivers for Sql-server connection via C/C++/java/PHP/etc.
Precisely, here are the Windows drivers for PHP.
Check out this page to know which version you need to get
They all exist in have 32 and x64, as well as "Thread safe" (ts) and "non-thread-safe" (nts) versions.
From what I read, nts versions are to be used if you work with IIS.
Usage :
Download and extract the package you need.
in my case, package 3.2, for php 5.6
Take necessary drivers
in my case, php_sqlsrv_56_ts.dll and php_pdo_sqlsrv_56_ts.dll
Put them in your php extensions directory
in my case, [...]\php5630vc11x86x170623162800\ext
If you wonder where this dir is inside your PHP, it should be quite easy to find, since you have plenty of other dlls here.
Likely, php_pdo_mysql.dll, php_pdo_pgsql.dll, etc.
Modify your php.ini
Be careful with Wamp, it seems to have one in the php directory AND another one in the apache dir.
Add lines to load the two extensions.
You can add them at the end of your file, or with the other extensions loading.
In my case, here's what I added :
;SQL-srever extensions
extension=php_sqlsrv_56_ts.dll
extension=php_pdo_sqlsrv_56_ts.dll
This part was for the PHP/PDO side.
For the driver to actualy work, you also need your (Windows) machine to have the ODBC drivers installed.
Feel free to try your connection already, but if it whines that you need the ODBC driver, go get it here :
Microsoft® ODBC Driver 11 for SQL Server®
And last, but not least, be sure to use the right format for your PDO connection.
$conn = new PDO ("sqlsrv:Server=$srv_host;database=$srv_dbname";
For comparison, here's what I wsa using on my linux server :
$conn = new PDO ("dblib:host=$srv_host:$srv_port;dbname=$srv_dbname", "$srv_username", "$srv_password");
I thought this syntax was common to all PDO drivers, but it appears I was wrong.
Here is the PHP PDO driver documentation.
I just actually had to do some work in php connecting to a MSSQL server. I did have to downgrade to php 5.4 due to the fact that the php_pdo_sqlsrv.dll is not updated for 5.5. For the dll files check here. But now down to the code I used to connect once you have the .dll files in the right place.
try {
$db = new PDO("sqlsrv:Server={$host};Database={$database}", $userName, $password);
}catch(PDOException $e){
die("failed to connect");
}
Just a standard PDO connection. Just in order to get it to work you must make sure that the .dll files are in the php directory.
I hope that answers at least part of the question.
I have worked with PHP 5.4 and SQL Server with PDO on Windows.
I strongly recommend using Microsoft's Web Platform Installer to set everything up. You can use it to install PHP, a local version of SQL Server Express to develop on, the official PHP driver for SQL Server, and IIS, all set up to work together.
One note of caution: The last release of the SQL Server PDO driver was in April, 2012. I reported a bug against it last year and was told that it's in "limited support", which apparently translates to "you're on your own". In any case, it worked reasonably well.

PHP to Oracle using oci8/MDB2 - _doConnect: unable to establish a connection

I'm running a Linux Fedora 19 setup with Oracle 11g, PHP 5.5.4, Apache 2.4.6, and PEAR 1.9.4. In addition to this, I have the OCI8 plug-in for PHP downloaded and enabled, and have downloaded MDB2 and the MDB2_Driver_oci8.
The goal is to connect my webpage to the Oracle 11g database. This already works in an existing setup (which I didn't do), and I'm trying to replicate it in a new setup.
For some reason, in the new server, it doesn't work. It generates an error:
_doConnect: [Error message: unable to establish a connection]
** oci8 (oci8)://gbsihr:xxx#localhost:1521/
An error occurred while trying to connect to the database server.
Error message: MDB2 Error: connect failed
I truly have no idea what this means. This is my PHP connect function:
<?php
include_once('includes/configure.inc');
require_once 'MDB2.php';
function DB_connect($intSilent = -1){
$db_dsn = $_SESSION['DB_Type'] ."://";
$db_dsn .= $_SESSION['DB_Username'] .":";
$db_dsn .= $_SESSION['DB_UserPassword'] ."#";
$db_dsn .= $_SESSION['DB_Host'] .":";
$db_dsn .= $_SESSION['DBPort'] ."/?service=";
$db_dsn .= $_SESSION['DB_DbName'];
if (PEAR::isError($dbconnect)) {
print '<pre>';var_dump($intSilent);print '</pre>';
print '<pre>';var_dump($db_dsn);print '</pre>';
print '<pre>';print $dbconnect->getDebugInfo();print '</pre>';
echo "An error occurred while trying to connect to the database server.<br>\n";
echo "Error message: " . $dbconnect->getMessage() . "<br>\n";
echo "A more detailed error description: " . $dbconnect->getDebugInfo() . "<br>\n";
exit();
// Check whether the object is a connection or
if($_SESSION["gENDebugInfo"] == "On"){
$_SESSION["gErrorNote"] = $dbconnect->getDebugInfo();
}
if ($intSilent < 0) {
header("Location:" . $_SESSION["gENWebRoot"] . "showerror.php?ec=1003"); // Failed to connect
exit();
}
}else{
$dbconnect->setOption('portability', MDB2_PORTABILITY_ALL);
}
return $dbconnect;
}
?>
And this is the contents of configure.inc:
$_SESSION["gENWebRoot"] = '/hrweb/';
$_SESSION['DB_Type'] = 'oci8';
$_SESSION['DB_Host'] = 'localhost';
$_SESSION['DB_Username'] = 'gbsihr';
$_SESSION['DB_UserPassword'] = 'ids21';
$_SESSION["DBPort"] = '1521';
$_SESSION['DB_DbName'] = 'xe';
As this works on another setup, I'm not sure where the error lies. OCI8 seems to be in order, though I did go through hoops to get it working.
I did do some research, with only two vague results - one pointing to the oci8.php itself, and the other, an Oracle TNS error (unlikely, given the lack of errors).
Here are my attempts to solve the problem:
I tried copying the Basic Query Example from this website. I modified the "hr" and "welcome", and ran it on my new setup (it works fine on the older one). And this is the result:
oci_connect(): OCIEnvNlsCreate() failed. There is something wrong with
your system - please check that ORACLE_HOME and LD_LIBRARY_PATH are
set and point to the right directories. Error while trying to
retrieve text for error ORA01804
I've also tried opening the httpd file in /etc/sysconfig/ and adding the following line to it:
LD_LIBRARY_PATH="/u01/apps/oracle/product/11.2.0/xe/lib
export LD_LIBRARY_PATH
And yet when I try to echo $LD_LIBRARY_PATH in the CLI, it won't return anything. It does appear in phpinfo(), though:
This is in contrast to $ORACLE_HOME, which I have to load manually every start-up by typing in . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh in the CLI, and does not appear under environments, but at least, can be echo'd.
There are a lot of variables in the old setup under environment; LD_LIBRARY_PATH, ORACLE_HOME, and ORACLE_SID being the most noteworthy. I only see LD_LIBRARY_PATH in the envvars file, though. Should I add them as well to the httpd file?
I'm not much of a Linux-person, sorry. Any help on this would be much appreciated.
I suggest you try to connect to your oracle database by using the plain oci8 functions and the same login parameters as you use for MDB2.
My guess is that this will fail as well, but might give you more error details.
Can you connect to oracle outside of php?
I presume you have a valid tns.ora file set up.
I needed these two lines set in my VirtualHost definition, note TNS_ADMIN is defined also, perhaps you do too:
SetEnv ORACLE_HOME /opt/oracle/instantclient
SetEnv TNS_ADMIN /usr/lib/oracle/11.2/client/network/admin/network/admin**
Just add this line
$dbconnect = DB::connect($db_dsn);
to function DB_connect
like this
...
$dbconnect = DB::connect($db_dsn);
if (PEAR::isError($dbconnect)) { ...

mysqli not working, module not found

I am new to PHP and web servers, and i was going to make a website using PHP. I found a free login script that uses mysqli. Every time I go on the page it says I don't have mysqli? I am running Apache with PHP3. The mysqli part of the script is thus:
// if the connection is successfully established
if($conn = new mysqli($this->conn_datas['localhost'], $this->conn_datas['daztestc_testdaz'], $this->conn_datas['dj2403ms81'], $this->conn_datas['daztestc_daztest'])) {
$sql = "SET NAMES 'utf8'";
$conn->query($sql);
$this->conn = $conn; // add the connection in the $conn property
}
php3? mysqli was not introduced until php5. where did you find a server with such an old copy of php? and is any of the code working? as most things have changed since php3.
Probably you don't have MySQLI extension installed. Check this page to know how to enable it. Ah... of course... you can't use it on PHP3... so if you really want, upgrade your server.

Setting sqlite3 database path using PDO

Having a hard time to figure out the path to set for my sqlite3 database using PDO in PHP.
My code as follows:
$handle = new PDO('sqlite:/C:/New folder/sqlite/test.db') or die("Could not open
database");
echo $handle;
$query = "SELECT * FROM student";
Debugging result:
It returns a blank web page instead of printing out the $handle. I already set my desired path where my sqlite database file was stored. What did i miss out ?
Kindly advise.
Firstly you need to know what PDO drivers are installed, make a blank file with in it:
<?php phpinfo(); ?>
Then look for the PDO section and you should see somthing along the lines of:
PDO drivers mysql, sqlite, sqlite2
If you only have mysql then you need to install the sqlite pdo driver. Use google for that, dont forget also check your production server too, else your create something you possibly cant use on your hosting.
As the PDO driver is much like the old sqlite_open() it will create the database file for you if its not found.
also as you may be aware spaces in file paths are not so good and can cause problems,
Instead of using:
sqlite:/C:/New folder/sqlite/test.db you should at least rename your New Folder to somthing else: sqlite:/New_folder/sqlite/test.db

Categories