I have no experience with access.
How to do update/insert/delete/select statement with and without $rs = new com("ADODB.RecordSet");
?
PDO
If you want to interface with an MS Access database using PHP, PDO is available for you.
<?php
try {
$pdo = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\accounts.mdb;Uid=Admin");
}
catch (PDOException $e) {
echo $e->getMessage();
}
When using PDO, due to the unified interface for DB operations, you have the opportunity to make your app more portable across various RDBMs systems. All you have to do is to provide the connection string to the PDO new instance and have the correct PDO driver installed.
As the result of this unified interface, your application can be easily ported from MS Access to MySQL, SQLite, Oracle, Informix, DB2, etc. which most certainly is the case if it ages enough.
Here's an insertion example:
<?php
try {
// Connect,
// Assuming that the DB file is available in `C:\animals.mdb`
$pdo = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\animals.mdb;Uid=Admin");
// INSERT data
$count = $pdo->exec("INSERT INTO animals(animal_type, animal_name) VALUES ('kiwi', 'troy')");
// echo the number of affected rows
echo $count;
// close the database connection
// See: http://php.net/manual/en/pdo.connections.php
$pdo = null;
}
catch (PDOException $e) {
echo $e->getMessage();
}
ODBC
In case you don't want to use PDO for some insane reasons, you can look into ODBC.
Here's an example:
<?php
if (! $conn = odbc_connect('northwind', '', '')) {
exit("Connection Failed: $conn");
}
if (! $rs = odbc_exec($conn, 'SELECT * FROM customers')) {
exit('Error in SQL');
}
while (odbc_fetch_row($rs)) {
echo 'Company name: ', odbc_result($rs, 'CompanyName'), PHP_EOL;
echo 'Contact name: ', odbc_result($rs, 'ContactName'), PHP_EOL;
}
odbc_close($conn);
Related
I have a strange problem. My server has been running PHP 5.6 for years no problem. (WinServer Std 2K8 SP2, IIS 6, MySQL 5.6 {separate server}, PHP 5.6)
We connect it to a DB2 server at our parent company. Today (2017-02-14) the ODBC connection (PDO_ODBC) started returning "could not find driver".
Excel is able to use the same ODBC connection to query the database - the ODBC connection is working.
I tried using both the PDO method and procedural method to connect. Failures in seeing the driver both ways.
From phpinfo():
ODBC Data
PDO Data
Code snippet:
$dsn = "odbc:workingODBCdsn";
$user = "xxxx";
$password = "yyyy";
$conn = null;
$results = array();
try {
$conn = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
die($e->getMessage());
}
if ($conn) {
$qry = $conn->query($sql);
if ($qry) {
$qry->setFetchMode(PDO::FETCH_ASSOC);
foreach ($qry as $row) {
$results[] = $row;
}
}
}
print "<pre>" . print_r($results, true) . "</pre>";
//ALT Method
$conn = odbc_connect($dsn, $user, $password);
$results = odbc_exec($conn, $sql);
print "<pre>" . print_r($results, true) . "</pre>";
Thanks in advance for any help.
Are you using the unixODBC or ibm_db2 (http://php.net/manual/en/ref.pdo-odbc.php)? It it recommended to use IBM DB2 Universal Database with “ibm_db2” extension. It’s faster and more efficient than using generic driver. It calls the native IBM DB2 functions with the extension.
Check out the db2_* functions from php.net IBM DB2 functions manual
Server's PHP instance switched from IIS to IISExpress. Switching it back to (full) IIS, and enduring all appropriate PDO drivers were enabled fixed the problem.
what is the best way for create a connection between PHP and SQL server that are seperate?(two server: server a SQL and server b PHP)
notice that I use wamp.
I read some articles like below but I want to know is there any new idea?
I test this code that works perfectly:
try{
$user = 'user';
$password = 'pass';
$server="localhost";//or server IP
$database="database";
$conn = odbc_connect("Driver={SQL Server};Server=$server;Database=$database;", $user, $password);
} catch (PDOException $e) {
echo "Failed : " . $e->getMessage() . "\n";
exit;
}
I use PDO_ODBC Method:
1- Install ODBC on server that has wamp and enable PHP_PDO_ODBC extension on your wamp
2- Use this code that supports UTF-8:
try{
$hostname = "IP";
$dbname = "database";
$username = "username";
$pw = "password";
$pdo = new PDO ("odbc:Driver={SQL Server Native Client 10.0};Server=$hostname;Database=$dbname; Uid=$username;Pwd=$pw;");
} catch (PDOException $e) {
echo "Failed : " . $e->getMessage() . "\n";
exit;
}
$query = $pdo->prepare("select field_name from table");
$query->execute();
for($i=0; $row = $query->fetch(); $i++){
echo iconv("CP1256","UTF-8", $row['field_name'])."<br>";
}
3- replace these Items with yours:
IP-database-username-password-field_name-table
4- sometimes you need use "SQL SERVER" instead of "SQL Server Native Client 10.0" and sometimes you need use "IP,port" instead of "IP" and sometimes you need use "ISO-8859-6" instead of "CP1256".
From the PHP manual: http://php.net/manual/en/pdo.construct.php
Example #1 Create a PDO instance via driver invocation
<?php
/* Connect to a SQL Server database using driver invocation */
$dsn = "sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName#12345abcde", "Password";
try {
$dbh = new PDO($dsn);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Just change the HOST ip to the IP and port of your mysql server.
I am trying to connect to MYSQL using php, but when I use the following command:
$link=mysql_connect("localhost","root","password");
and echo $link, it gives me Resource id #98. What does this mean? Am I not connected?
Okay, I guess it sounds like the connection is okay. Now, with the following code, I am not seeing any changes in the mysql database. Why could that be?
<?php
$conn=new mysqli("localhost","root","password","database");
$sql="INSERT INTO chat_active (user, time)
VALUES('John', '1234')";
?>
What makes you think you are not connected?
According to the docs, mysql_connect()
[r]eturns a MySQL link identifier on success or FALSE on failure.
Since it did not return FALSE, but rather a resource identifier, that means the connection was successful.
Also note that the mysql extension is deprecated since PHP 5.5.0 as MortimerCat pointed out. Instead you should look into the MySQLi or the PDO extension.
"Now, with the following code, I am not seeing any changes in the mysql database. Why could that be?"
As per your edit which you are now using mysqli_ to connect with, and that you're saying that you're not seeing any changes in your database, is because:
You're not passing the DB connection to your query and it is required when using mysqli_.
Rewrite, with a few more goodies:
<?php
$conn=new mysqli("localhost","root","password","database");
// Check if you've any errors when trying to access DB
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$sql="INSERT INTO chat_active (user, time) VALUES ('John', '1234')";
$result = $conn->query($sql);
// Check if you've any errors when trying to enter data in DB
if (!$result)
{
throw new Exception($conn->error);
}
else{
echo "Success";
}
Read the manual http://php.net/manual/en/mysqli.query.php
Once you've grasped that, get to know mysqli with prepared statements, or PDO with prepared statements, they're much safer.
References:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/language.exceptions.php
Footnotes:
Your column names user, time suggests that you're trying to enter a string and what appears to be and to be intended as "time" and that the user column is set to varchar.
Make sure that you haven't setup your time column other than a datetime-related type, otherwise MySQL may complain about that.
MySQL stores dates as YYYY-mm-dd as an example.
Visit https://dev.mysql.com/doc/refman/5.0/en/datetime.html in regards to different date/time functions you can use.
MySQL references:
https://dev.mysql.com/doc/refman/5.0/en/char.html
https://dev.mysql.com/doc/refman/5.0/en/data-types.html
https://dev.mysql.com/doc/refman/5.0/en/datetime.html
You yould use mysqli or PDO.
Here's a connection example with PDO:
<?php
$dbuser = 'user';
$dbpasswd = 'passwd';
$dbname = 'dbname';
try {
$gbd = new PDO("mysql:host=localhost;dbname=$dbname;charset=utf8", $dbuser, $dbpasswd);
$gbd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
}
PDO CRUD examples:
//INSERT
try {
$sentence = $gbd->prepare("INSERT INTO table (param1, param2) VALUES (:param1, :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//SELECT
try {
$sentence = $gbd->prepare("SELECT param1,param2 FROM table WHERE param1 = :param1 AND param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
while ($row = $sentence->fetch(PDO::FETCH_ASSOC)){ //Also available FETCH_NUM,FETCH_BOTH AND OTHERS
$result['param1'] = $row['param1'];
$result['param2'] = $row['param2'];
}
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//UPDATE
try {
$sentence = $gbd->prepare("UPDATE table SET param1 = :param1, param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//DELETE
try {
$sentence = $gbd->prepare("DELETE table WHERE param1 = :param1 AND param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
And here's PDO manual
http://php.net/manual/en/book.pdo.php
u are not executing that query.u are only declaring that query.
for execution do--
$conn->query($qry);
it will,execute ur query.
I am Developing the simple application,the application related to database operations.
My doubt is how can i connect to multiple databases same time.
how can php knows which databases the data will store.
If the user enter the data which database it will enter,both databases or one database.
Please answer my question.i have struggling a lot for this question.
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
try {
$db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
(Of course replace databasename, username and password above)
You can then query the database like this:
$result = $db->query("select * from tablename");
foreach ($result as $row) {
echo $row['foo'] . "\n";
}
Or, if you have variables:
$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();
If you need multiple connections open at once, you can simply create multiple instances of PDO:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
Yes you can.. by using two connection strings..
$mysqli1 = new mysqli('HOST1', 'USER1', 'PASSWORD1', 'DB_NAME1');
$mysqli2 = new mysqli('HOST2', 'USER2', 'PASSWORD2', 'DB_NAME2');
and your queries should be like
$result1 = $mysqli1->query('query ......');
and
$result2 = $mysqli2->query('query ......');
Of course you can given example below add more connections if you want:
Class database
{
private oracleDatabase;
private mysqlDatabase;
public function connOracle() {
$db = "";
$user = "";
$password = "";
try {
$this->oracleDatabase = new PDO("oci:dbname=".$db,$user,$password);
} catch(PDOException $e){
echo "Can't connect to database (Oracle). ". $e->getMessage();
}
}
public function connMysql() {
$db = "";
$user = "";
$password = "";
try {
$this->mysqlDatabase = new PDO("mysql:dbname=".$db,$user,$password);
} catch(PDOException $e){
echo "Can't connect to database (Mysql). ". $e->getMessage();
}
}
}
Be carefull if you are using two databases on the same server at the same time. By default mysql_connect returns the same connection ID for multiple calls with the same server parameters, which means if you do
<?php
$db1 = mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);
?>
then $db1 will actually have selected the database 'db2', because the second call to mysql_connect just returned the already opened connection ID !
You have two options here, eiher you have to call mysql_select_db before each query you do, or if you're using php4.2+ there is a parameter to mysql_connect to force the creation of a new link.
Use this below link to refer.What you have asked here.
PHP Documentation
Yes, you may use multiple database in one application, but the main thing is when you are communicating with the dbname, you have to specify that dbname also so than script will communicate with only that db in which you had defined. Ex.
$db1 = mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);
$resultsa = mysql_query('SELECT * FROM table_a', $dbname) or die('Could not query database_a');
Yes you can connect multiple databases.
open your php.ini file and give me your database details like
port number,username,password.
And after that you can give the queries like this in your applications
$db1 = mysql_connect($hostname, $username, $password);
$db2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $db1);
mysql_select_db('database2', $db2);
Then to query database 1, do this:
mysql_query('select * from tablename', $dbh1);
and for database 2:
mysql_query('select * from tablename', $dbh2);
i think this is work fine for your question.
Yes you can, in very basic terms, you do it like this:
http://au1.php.net/function.mysql-connect
$conn = mysql_open($host, $username, $password, true);
To connect to multiple databases on the same server:
$dblink1 = mysql_select_db('database_a', $conn);
$dblink2 = mysql_select_db('database_b', $conn);
To get results from two databases:
$resultsa = mysql_query('SELECT * FROM table_a', $dblink1) or die('Could not query database_a');
$resultsb = mysql_query('SELECT * FROM table_b', $dblink2) or die('Could not query database_b');
edit - keep in mind that the mysql_ functions aren't available in recent PHP releases because they've been removed.
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information.
I am starting learn PDO with MS SQL Server.
Connecting with this code:
$userDB = 'userBD';
$passwordDB = 'passwordDB';
try {
$DBH = new PDO('mssql:dbname=spr_bank;host=hostname', $userDB, $passwordDB);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo "<h1 style='font-weight:bold; color:red;'>Error. Can not connect to Database</h1>";
file_put_contents('PDOErrors.log', date("Y-m-d H:i:s")." - ".$e->getMessage()."\n", FILE_APPEND);
exit();
}
and now, I select data from table:
//simple query and binding with results
$query = $DBH->prepare("SELECT name FROM spr_sotrudnik WHERE login = :login AND password = :password");
$login = (isset($_POST['login']) === true) ? $_POST['login'] : '' ; // ? : shorthand for if else
$password = (isset($_POST['password']) === true) ? md5($_POST['password']) : '' ; // ? : shorthand for if else
// bind parameters - avoids SQL injection
$query->bindValue(':login', $login);
$query->bindValue(':password', $password);
//try... if not catch exception
try {
// run the query
$query->execute();
while($rows = $query->fetch()){
echo $rows["name"];
}
}
catch(PDOException $e){
echo $e->getMessage(), $e->getFile(), $e->getLine();
}
When I go to the browser, I get this error:
SQLSTATE[HY000]: General error: 10007 Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier. [10007] (severity 5) [(null)]D:\www\sklad_new\inc\auth.php19
When I write this query
$query = $DBH->prepare(" SELECT CONVERT(VARCHAR(MAX),name) AS s FROM spr_sotrudnik WHERE login = :login AND password = :password");
I have no error, but I see "?????"
How can I change this?
You're omitting the charset parameter in the DSN string:
$DBH = new PDO('mssql:dbname=spr_bank;host=hostname', $userDB, $passwordDB);
... so you're probably using default encodings along the whole toolchain.
In any case, the PDO_DBLIB driver is clearly tagged as experimental and includes this notice:
On Windows, you should use SqlSrv, an alternative driver for MS SQL is
available from Microsoft: »
http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx .
If it is not possible to use SqlSrv, you can use the PDO_ODBC driver
to connect to Microsoft SQL Server and Sybase databases, as the native
Windows DB-LIB is ancient, thread un-safe and no longer supported by
Microsoft.
In my experience, this means that you can obtain all sort of unpredicted side effects.