Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

PHP and Microsoft Access database - Connection and CRUD

I have no experience with access.

How to do update/insert/delete/select statement with and without $rs = new com("ADODB.RecordSet"); ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...