how do I replace MS Access with SQLite in PHP - php

I am porting a site running PHP with an MS Access DB on a windows machine to a Mac with an SQLite DB.
the original PHP script uses the following code to connect to the database:
$db = 'S:\~myhome\mydata.mdb';
$conn = new COM('ADODB.Connection');
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$db");
What would be the SQLite equivalent?
Edit:
I tried
$db = 'sqlite:'.__DIR__.'/mydata.sqlite';
$conn = new PDO($db) or die("cannot open the database");
but it didn't work

Like Python, PHP has a built in SQLite library. Current versions support SQLite3. First, uncomment out the php_sqlite extension in the .ini file. Then, simply, call a new object:
<php
$conn = new SQLite3($db);
$results = $conn->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>
Of course as suggested you can use PDO or mysqli database connections.

Since you have to work on it anyway, I suggest to use PDO. This is a standard PHP library with drivers for several database types.
For a quick start see http://www.phptherightway.com/#databases, there's a short example about SQLite as well.

after much searching I found the answer:
include '/usr/share/php/adodb/adodb.inc.php';
$path = urlencode(__DIR__.'/mydata');
$dsn = "sqlite://$path/?persist"; # persist is optional
$conn = ADONewConnection($dsn);

Related

How can I connect from a website to a Microsoft SQL Database using PHP

Ive worked with the typical PHPMyAdmin interface until now when it comes to databases.
Now Ive been handed a .bak file and pointed to "Microsoft SQL Server Managment Studio" and told to use that.
My problem is that I dont know how to do the most basic things. For instance when I want to connect to a PHPMyAdmin Database I know that I need to define the host, the user, the password and the database and throw that information into a mysqli_connect() and thats that.
So my question is:
How do I connect to my database that I have in my SQL Server Managment Studio? The same way I did before? And if so where do I find the needed information like host, user, password?
I would install the SQLSRV PDO extension. Then use a similar methodology to access the database
$database = "";
$server = "";
$conn = new PDO( "sqlsrv:server=$server ; Database = $database", DB_USER, DB_PASSWORD);
$sql = "SELECT * FROM Table WHERE MemberID =:MemberID";
$iMemberID = 5;
$st = $conn->prepare($sql);
//named placeholders within the execute() as an array.
$st->execute(array(':MemberID'=>$iMemberID));
//OR using bind param..
$st->bindParam(':MemberID', $iMemberID);
while ($row = $st->fetch()){
echo "<pre>";
var_dump($row);
echo "</pre>";
}

Remote connection to MySQL works via command line, but fails when using php's mysql_connect from a web browser

I am trying to connect to a MySQL server using PHP's 'mysql_connect()' function, but the connection fails. This is my code:
$con = mysql_connect("example.net", "myusername","") or die("Could not connect: ".mysql_error());
I placed this code inside a PHP script, which I try to open using a web browser (the script is stored on a remote host which has PHP enabled) but it doesn't work. It doesn't return the die error either. Echoing something before the $con successfully outputs in the browser, whereas nothing outputs after that line. If I type:
mysql -h example.net -u myusername
from a remote machine, I could connect to the DB without any problem and do queries and other modifications.
Update :
I also tried this after some suggestion, but no improvement:
<?php
$usern = "myusername";
$dbh = new PDO('mysql:host=servername.net;dbname=test', $usern, "");
echo $usern;
?>
What operating system is the remote host running PHP using? Perhaps MySQL isn't enabled in php.ini. Also, please don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process (see the red box). Instead, you should learn about prepared statements and use either PDO or MySQLi. If you can't decide which, this article will help you. If you care to learn, this is a good PDO tutorial.
Have you tried using PDO or the MySQLi interface? If you're trying to learn PHP, you should not be using the mysql_* functions regardless. See if you can access the database by using a line similar to this:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
If you need more detailed documentation, this code comes directly from the documentation itself.
EDIT: Also, try using PDO's error checking functionality. This example creates a database connection using PDO and tries to perform a simple query. It doesn't use prepared statements or any of those features, so it's not production-ready code (i.e. *don't just throw this into your code without understanding how to improve it) and you'll need to edit it to include a SELECT query that's relevant to your database, but it should at least tell PDO to provide more information about the errors it encounters.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM booksa";
$q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorInfo()));
$r = $q->fetch(PDO::FETCH_ASSOC);
print_r($r);
?>
Is the php file located on the same server as the mysql database, if so you might have to use 'localhost' as the first argument for mysql_connect() instead the external address.

php adodb MSSQL connection

I have a linux server that I'm trying to use php adodb to connect to a MSSQL server.
include('adodb5/adodb.inc.php');
$conn =& ADONewConnection('odbc_mssql');
$dsn = "Driver={SQL Server};Server=MSSERVER;Database=Northwind;";
$conn->Connect($dsn,'sa','password')or die("Unable to connect to server");
I've install mssql through yum etc and I know the server can connect to it as I've tried the following:
$db = #mssql_connect("MSSERVER","sa","password") or die("Unable to connect to server");
mssql_select_db("Northwind");
// Do a simple query, select the version of
// MSSQL and print it.
$version = mssql_query('SELECT ##VERSION');
$row = mssql_fetch_array($version);
echo $row[0];
// Clean up
mssql_free_result($version);
Any ideas why my adodb wont connect, or any examples on how I can connect would be much appreciated.
I've solved this by looking at this forum: http://ourdatasolution.com/support/discussions.html?topic=4200.0
The correct code is:
<?php
include("adodb5/adodb.inc.php");
//create an instance of the ADO connection object
$conn =&ADONewConnection ('mssql');
//define connection string, specify database driver
$conn->Connect('xxx.xxx.x.xxx:1400', 'user', 'password', 'DbName');
//declare the SQL statement that will query the database
$query = "select * from table";
$rs = $conn->execute($query);
//execute the SQL statement and return records
$arr = $rs->GetArray();
print_r($arr);
?>
Hope that helps somebody else.
With php 5.3 of above the php_mssql modul is no longer supported for windows.
A Solution is to download the MicroSoft PHP Driver from http://www.microsoft.com/en-us/download/details.aspx?id=20098.
This installer will extract the modul dll files to you php extension directory.
Include the correct version in you php ini (e.g. like this for php 5.3 ThreadSafe):
extension=php_sqlsrv_53_ts.dll
After this you can use adboDb again, but you have to use mssqlnative as adodbtype.
And the connection with ip and port didnt work for me, but ipaddress\\SERVERNAME worked (see examplecode)
<?php include("adodb5/adodb.inc.php");
//create an instance of the ADO connection object
$conn =&ADONewConnection ('mssqlnative');
//define connection string, specify database driver
// $conn->Connect('xxx.xxx.x.xxx:1400', 'user', 'password', 'DbName');
$conn->Connect('xxx.xxx.x.xxx\\SERVERNAME', 'user', 'password', 'DbName');
//declare the SQL statement that will query the database
$query = "select * from table";
$rs = $conn->execute($query);
//execute the SQL statement and return records
$arr = $rs->GetArray();
print_r($arr); ?>
For PHP 7.4 you can download the drivers here:
https://learn.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-ver15
Copy the files to the ext directory of your php installation.
In the php.ini file then add the extensions as follows:
extension=php_pdo_sqlsrv_74_ts_x64
extension=php_sqlsrv_74_ts_x64
The extension also requires the ODBC driver for SQL Server to be installed:
https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver15

How to retrieve data for a webpage from an MS Access database with password

I have an MS Access database file that I want to copy into a MySQL to serve up on a webpage, the problem is the database is passworded. What I want to do is upload the file to the server then either strip the password or open it using the password so I can then copy it across to MySQL.
The password is known and cannot be removed at source.
I would like to do this with PHP if possible.
This is a recurring event, at max twice a day.
Having contacted my hosting the only way to use odbc is to upgrade to dedicated hosting at 10x the price of my current hosting. Looks like this one is a no go unless I can get at the data another way.
To open it, the password should be passed along in the connection string... For PHP using odbc_connect, the syntax is available here. Since you say the password is known, this should work.
To remove it completely, you'd want to just open it in Access and save a copy without the password. I'm not sure that this can be automated easily. If you need to access the data and transfer it repeatedly, I'd say stick with the password int he connection string.
Example from the article linked to:
<?php
// Microsoft SQL Server using the SQL Native Client 10.0 ODBC Driver - allows connection to SQL 7, 2000, 2005 and 2008
$connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
// Microsoft Access
$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);
// Microsoft Excel
$excelFile = realpath('C:/ExcelData.xls');
$excelDir = dirname($excelFile);
$connection = odbc_connect("Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=$excelFile;DefaultDir=$excelDir" , '', '');
?>
Here is the DSN - Less connection code sample :
<?php
$db_connection = new COM("ADODB.Connection");
$db_connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("../databases/database.mdb") ." ;DefaultDir=". realpath("../databases");
$db_connection->open($db_connstr);
$rs = $db_connection->execute("SELECT * FROM Table");
$rs_fld0 = $rs->Fields(0);
$rs_fld1 = $rs->Fields(1);
while (!$rs->EOF) {
print "$rs_fld0->value $rs_fld1->value\n";
$rs->MoveNext(); /* updates fields! */
}
$rs->Close();
$db_connection->Close();
?>

PHP to SQL Server without ODBC or MSSQL support

I'm in a situation where my Windows hosting has PHP support, but the PHP is not configured to support ODBC or MSSQL. I can't get them to change that, so I'm wondering if there's a way to connect to SQL Server through other means - maybe including some files that provide the functions that I'd need?
Leaving it up here in the hopes that it will make it easier for other people to get around this type of limitation.
Copied here for completeness:
<?php
$db = new COM("ADODB.Connection");
$dsn = "DRIVER={SQL Server}; SERVER={SERVER};UID={USER};PWD={PASS}; DATABASE={DB}";
$db->Open($dsn);
$rs = $db->Execute("SELECT * FROM table");
while (!$rs->EOF)
{
echo $rs->Fields['column']->Value."<BR>";
$rs->MoveNext();
}
?>

Categories