PHP and Microsoft Access database - Connection and CRUD

前端 未结 1 1028
我寻月下人不归
我寻月下人不归 2020-11-30 09:49

I have no experience with access.

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

相关标签:
1条回答
  • 2020-11-30 10:06

    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);
    
    0 讨论(0)
提交回复
热议问题