Cant connect to access database via php - php

I'm really in need of assistance with this issue, ive been trying for days. I have an access database which i'm trying to query via PHP - i have come to this forum because after reading many posts and trying different things i am certain that this is some kind of issue on the server.
I have installed Microsoft access database engine, both 2010 and the 2007 version but whatever i try i get the same error message :
Uncaught exception 'com_exception' with message '<b>Source:</b> ADODB.Connection<br/><b>Description:</b> Provider cannot be found.
I have uncommented all the relative lines in php.ini (after crawling through many stack overflow posts with the same issue) but with no success. Below is the code i am using in my php file.
<?php
// Create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");
// Define the connection string and specify the database driver
$connStr = "PROVIDER=Microsoft.Ace.OLEDB.12.0;Data Source=".realpath("HS_BE.accdb").";";
// Open the connection to the database
$conn->open($connStr);
// Declare the SQL statement that will query the database
$query = "SELECT * FROM Accommodation";
// Execute the SQL statement and return records
$rs = $conn->execute($query);
$num_columns = $rs->Fields->Count();
echo $num_columns . "<br>";
for ($i=0; $i < $num_columns; $i++) {
$fld[$i] = $rs->Fields($i);
}
echo "<table>";
while (!$rs->EOF) // Carry on looping through while there are records
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $fld[$i]->value . "</td>";
}
echo "</tr>";
$rs->MoveNext(); // Move on to the next record
}
echo "</table>";
// Close the connection and recordset objects freeing up resources
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;
?>
Id be very grateful for some assistance!

Related

How to make Pervasive PDO PHP connection

I am trying to establish a connection to my works Pervasive SQL database. I've tried using odbc_connect (didn't work) but I was told that PDO is easier and better (HA, also didn't work). This is my connection string
$dbh = new PDO("odbc:Driver={Pervasive ODBC Client Interface};ServerName=192.168.43.19;dbq=GLOBALTST");
I've tried odbc:DSNname (https://www.php.net/manual/en/ref.pdo-odbc.connection.php), ODBC:servername (ip and hostname), and odbc:databasename. Nothing has worked. This is the error I am getting:
Fatal error: Uncaught PDOException: SQLSTATE[IM003] SQLDriverConnect: 160 Specified driver could not be loaded due to system error 1114: A dynamic link library (DLL) initialization routine failed. (Pervasive ODBC Client Interface, C:\PSQL\bin\w3odbcci.dll). in C:\inetpub\wwwroot\default.php:4 Stack trace: #0 C:\inetpub\wwwroot\default.php(4): PDO->__construct() #1 {main} thrown in C:\inetpub\wwwroot\default.php on line 4
The DLL it is looking for is actually located in the spot it's referencing. as far as I can tell there are no issues with it. THe ODBC is configured correctly on the server and I can connect to the DB in the PSQL control center. can anyone help in identifying my issue or pointing to a connection string that works either odbc_connect or PDO?
This code worked for me using PSQL v11 64 bit ODBC, PHP 7.2 64 bit on a Windows machine.
<?php
try {
// Connect to the data source
//$dbh = new PDO($dsn);
$dbh = new PDO("odbc:Driver={Pervasive ODBC Interface};ServerName=192.168.43.19;dbq=demodata");
$stmt = $dbh->prepare('SELECT * FROM class');
// Execute the prepared statement for each name in the array
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$numResults = count($result);
echo ('<b>Total Results: </b> ' . $numResults . '<br>');
if ($numResults > 0) {
// Output the table header
echo '<table><tr>';
foreach ($result[0] as $fieldName=>$value) {
echo '<th>' . htmlspecialchars($fieldName) . '</th>';
}
echo '</tr>';
// Now output all the results
foreach($result as $row) {
echo '<tr>';
foreach ($row as $fieldName=>$value) {
echo '<td>' . htmlspecialchars($value) . '</td>';
}
echo '</tr>';
}
// Close the table
echo '</table>';
} else {
echo 'No results';
}
// Close statement and data base connection
$stmt = NULL;
$dbh = NULL;
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>

Is there a way to utilize an Oracle wallet via PHP on windows?

I have a PHP codebase that resides on a Windows server that connects to an Oracle database. My database is moving to a Oracle in the cloud setup that requires us to use an Oracle wallet to connect.
I got the setup for the wallet and can connect via the utilities, but all my research thus far has me using oci_connect() with a session_mode of OCI_CRED_EXT. But PHP's oci_connect (https://www.php.net/manual/en/function.oci-connect.php) states "OCI_CRED_EXT is not supported on Windows for security reasons.".
Is there a way to utilize an Oracle wallet via PHP on windows?
The Oracle Cloud wallets provide mutual TLS for security but you still need to pass a DB username and password. Hence you don't use external authentication.
You just need to make sure that Oracle Net can find the wallet, either with the Easy Connect Plus syntax used below (wallet_location is the dir containing the cwallet.sso file), or by editing sqlnet.ora (or putting it in a default location). See How to connect to Oracle Autonomous Cloud Databases.
Code that works for me is:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
$c = oci_connect('cj', 'topsecret', 'tcps://adb.ap-melbourne-1.oraclecloud.com:1522/xxxxxx.adb.oraclecloud.com?wallet_location=/Users/cjones/Cloud/alwaysfree/CJDBMELB');
if (!$c) {
$m = oci_error();
trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}
$s = oci_parse($c, "select * from dual");
if (!$s) {
$m = oci_error($c);
trigger_error('Could not parse statement: '. $m['message'], E_USER_ERROR);
}
$r = oci_execute($s);
if (!$r) {
$m = oci_error($s);
trigger_error('Could not execute statement: '. $m['message'], E_USER_ERROR);
}
while (($row = oci_fetch_array($s, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo "<td>";
echo $item!==null?htmlspecialchars($item, ENT_QUOTES|ENT_SUBSTITUTE):" ";
echo "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>

I am not able to execute select records from a table in database in google sql cloud using php

<?php
define('DB_NAME', 'xp_database'); // DATABASE
define('DB_USER', 'valli'); // ROOT DEFAULT MYSQL
define('DB_PASSWORD', 'Valli123'); // PASSOWORD
define('DB_HOST', '127.0.0.1'); // LOCAL IF YOU USE LOCAL.
$data=array();
$i=1;
$link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
else
{
echo "Connected to database";
}
// Attempt select query execution
$sql = "show databases";
if($result = mysqli_query($link, $sql))
{
if(mysqli_num_rows($result) > 0)
{
echo "<table>";
echo "<tr>";
echo "<th>userid</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['user_id'] . "</td>";
echo "</tr>";
// Free result
//set mysqli_free_result($result);
}
}
else
{
echo "No records matching your query were found.";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
I have enabled the Admin API in google cloud.
Connection is successful. But retrieval using select query is not successful. Please tell me what is missing in this. Is there any other setting that I have to do. I have migrated the data from local database to mysql cloud database.
If you are using App Engine to connect to Cloud SQL, bear in mind that you will need to enable Cloud SQL proxy since Google App Engine connects from inside of Google servers to your Cloud SQL instance via proxy.
Nonetheless, if what you would like to do is connect from outside with pure PHP code, you can still do it without using the Cloud SQL proxy.
For connecting from outside using pure PHP code you will need to authorize your IP from your Cloud SQL instance, as shown here.
Then, you should modify your code in order to change localhost or 127.0.0.1 to your Cloud SQL instance public IP (taking into account the other variables like username, password and the database name that you would like to connect to).
For finding your Cloud SQL's public IP, you can refer to here.
Finally, if you would like to look around PHP on Google App Engine, you can do it by checking the documentation here.
I hope this helps.

iTunes Search API: Update Notification

i'm using iTunes API Search and Advanced Custom Field WordPress plugin so the wp author can add a mac app id to a custom field and the implanted iTunes Search API above will add all the other information of app automatically in the wp post. and when app information updated my wp post will have the updated info like last verion number app size and ...
but the problem is my own wrote review and guide of any verion of any app inside my website and it need to be updated manually.
for example i have added a post for version 3.7.1 of "Things 3" mac app using method above to my WordPress and i have reviewed this version with my own description and hand-wrote in the post.
now i need to get notified when ever this app gets a new version or update so i can update my review and add some text for new version inside the post as well.
is there any way or method you guys can think of, so i can get notified when ever an app i have reviewed in my site gets an update ?
i really appreciate any way or taught !
Thanks.
There is no native API to do what you're asking.
However, with a little coding I believe you could use the RSS feed of the application to then create something to notify you on a change.
See Example for the App HomeScan
https://itunes.apple.com/lookup?id=1380025232
ID= YOURAPPID
I believe this should give you some general direction to do what you need.
This is a reply to our comment history in the other answer.
#erfanMHD, there are a number of ways to really do this. You don't have to do it in javascript. This isn't really something someone can give you an easy code snippet for since it requires a few additional things and is generally frowned upon in StackOverflow.
You'll need somewhere to store the localVersion of the application of the review you last wrote. In the example I wrote below I used a simple MySQL database to hold the local version. You'll also need to figure out how you want to display the data. I know you can add stuff to the wordpress dashboard but this isn't something we can show you how to do via StackOverflow.
However, below is a very simple (JUST FOR REFERENCE) purposes only on how one could achieve what you're trying to do. However this is just an example to guide you along the process.
For this demo, you'll need a MySQL database with a DBName of test and and a record created called application_version with 3 rows. ID, Name, Version.
<?php
$servername = "localhost"; // Your MySQL Server
$username = "root"; // Your MySQL Username
$password = "password"; // Your MySQL Password
$dbname = "test"; // The name of your MySQL database
$id = "904280696"; // The ID of the applicaiton you're wanting to check
function search($searchTerm){
// Construct our API / web services lookup URL.
$url = 'https://itunes.apple.com/lookup?id=' . urlencode($searchTerm);
// Use file_get_contents to get the contents of the URL.
$result = file_get_contents($url);
// If results are returned.
if($result !== false){
// Decode the JSON result into an associative array and return.
return json_decode($result, true);
}
// If we reach here, something went wrong.
return false;
}
function updateVersion($id, $name, $version) {
// Create MySQL connection
$conn = new mysqli($GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
// Check MySQL connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Save the Version information
$sql = "UPDATE application_version SET name='" . $name . "', version='" . $version . "' WHERE id='" . $id . "'";
echo $sql;
echo "<br>";
// Run the Insert into MySQL
if ($conn->query($sql) === TRUE) {
// Print On Success
echo "Record Updated Successfully";
echo "<br>";
} else {
// We dun goofed
echo "Error: " . $sql . "<br>" . $conn->error;
echo "<br>";
}
$conn->close();
}
function getLocalVersion($id) {
// Create MySQL connection
$conn = new mysqli($GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
// Check MySQL connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM application_version WHERE ID = " . $GLOBALS['id'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "Found Application ID Entry in database";
echo "<br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Version</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td>".$row["version"]."</td></tr>";
$GLOBALS['storedVersion'] = $row["version"];
}
echo "</table>";
echo "<br>";
} else {
echo "No Application ID Entry found in database";
echo "<br>";
}
$conn->close();
}
// Search for your requested ID
$searchResults = search($GLOBALS['id']);
$currentVersion = '0.0.0';
$storedVersion = '0.0.0';
$appName = 'null';
// Loop through the results.
foreach($searchResults['results'] as $result){
// Pass the current version to variable
$currentVersion = $result['version'];
$appName = $result['trackName'];
// Get the current version or what ever else information you need
echo 'Current Version: ' . $currentVersion;
echo "<br>";
echo "<br>";
}
// Get Local Version from database
getLocalVersion($id);
if ($currentVersion > $storedVersion) {
echo "You have an old version friend";
echo "<br>";
// Write what you want it to do here
updateVersion($id, $appName, $currentVersion);
} else {
echo "You're all up to date";
echo "<br>";
// Write what you don't want it to do here
}
?>
Again, this is just quick and dirty. You'd want to do a lot of additional checks and balances. One I see right off the bat would be in the check for inserting.

PHP 5.5.24 MySQLi persistent connection returns 'couldn't fetch mysqli'

I want to avoid reconnecting database for every query in same page aka want to reuse the connection result once mysqli_connect so I can speed up the results. I tried "p:" in front of hostname. But still I am getting below warnings. I get expected results when I connect without persistent "p:" and connect on every query.
Warning: mysqli_close(): Couldn't fetch mysqli in C:\xampp\htdocs\TodayReport\tr1.php on line 99
Notice: Undefined variable: Result1Con in C:\xampp\htdocs\TodayReport\tr1.php on line 142
Warning: mysqli_close() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\TodayReport\tr1.php on line 142
I referred below pages.
How to use mysqli persistent connection across different pages
Php Mysqli Persistent connection error
Below is my script (i've minimized to be able to read quickly)
<?php
$webpage = "<!DOCTYPE html><html><head><title>Record Count</title><script src='sorttable.js'></script></head>";
$FirstProjectTitle = "Result1";
$SecondProjectTitle = "Result2";
//constructing HTML layout
Global $LoginDetailsCon;
Global $LoginDetailsResult;
$LoginDetailsCon=mysqli_connect("p:98.168.2.14","root","root#123","resultdbmain") or die("Failed to connect to resultdbmain: " . mysqli_connect_error());
$LoginDetailsQuery="SELECT * FROM login WHERE `IsWorking` = 1 AND `level` = 1";
$LoginDetailsResult=mysqli_query($LoginDetailsCon,$LoginDetailsQuery);
while ($row=mysqli_fetch_array($LoginDetailsResult,MYSQLI_ASSOC)) {
$Result1Con=mysqli_connect("98.168.2.14","root","root#123","resultdb1") or die("Failed to connect to resultdb1: " . mysqli_connect_error());
$result1Query="SELECT * FROM `resultdb1table1` WHERE `SID` = " . $row["ID"] ." AND `KeyDate` > '" . date("Y-m-d") . " 00:00:00' ";
$result1Result=mysqli_query($Result1Con,$result1Query);
$i=0;
$ik=0;
$SName = $row["Name"];
while ($row=mysqli_fetch_array($result1Result,MYSQLI_ASSOC)) {
$i++;
$ik = $ik + $row["KeyStroke"];
if ($i==1) {
$started=$row["KeyDate"];
}
$Lastkeyed=$row["KeyDate"];
}
if ($i > 0) {
//constructing HTML layout with results
}
}
$webpage .= "</table>";
mysqli_close($Result1Con);
//$LoginDetailsCon=mysqli_connect("98.168.2.14","root","root#123","resultdbmain");
//if (mysqli_connect_errno()) { echo "Failed to connect to resultdbmain: " . mysqli_connect_error(); }
//$LoginDetailsQuery="SELECT * FROM login WHERE `IsWorking` = 1 AND `level` = 1";
//$LoginDetailsResult=mysqli_query($LoginDetailsCon,$LoginDetailsQuery);
while ($row=mysqli_fetch_array($LoginDetailsResult,MYSQLI_ASSOC)) {
$Result2Con=mysqli_connect("98.168.2.14","root","root#123","resultdb2") or die("Failed to connect to resultdb2: " . mysqli_connect_error());
$result2Query="SELECT * FROM `resultdb2table1` WHERE `ID` = " . $row["ID"] ." AND `KeyDate` > '" . date("Y-m-d") . " 00:00:00' ";
$result2Result=mysqli_query($result2Con,$result2Query);
$i=0;
$ik=0;
$UName = $row["Name"];
while ($row=mysqli_fetch_array($result2Result,MYSQLI_ASSOC)) {
$i++;
$ik = $ik + $row["KeyStroke"];
if ($i==1) {
$started=$row["KeyDate"];
}
$Lastkeyed=$row["KeyDate"];
}
if ($i > 0) {
//constructing HTML layout with results
}
}
mysqli_close($result2Con);
mysqli_close($LoginDetailsCon);
$webpage .= "</body></html>";
echo $webpage ;
?>
Your idea on database connections is quite err... unusual.
Surely you don't have to reconnect for every query in same page. But you don't need multiple connections for this either. Just use one single connection.
As a matter of fact, you don't have to (and should not) connect every time you runs a query. Instead, you should connect only once per script execution, and then use that single connection variable all the way through your code.
So, create a file called connection.php, place your connection code there once, and then include it in every script that requires database interaction.
Also, do not call mysqli_close(). PHP will close connection for you.
And forget about persistent connections for a while. You don't need it.

Categories