You can connect to MySQL from PHP using Devart ODBC Driver for MySQL.
1. In the php.ini file, uncomment the extension=odbc line.
2. Restart your web server to apply the changes.
An ODBC connection requires a connection string, which can either use a predefined DSN or be specified through connection string parameters (a DSN-less connection).
For information about available parameters, see Connection string parameters.
You can use a connection string with a predefined DSN.
$connectionString = "DSN=your_dsn";
If you need credentials other than those used in the DSN, specify them in the connection string to override the DSN values.
$connectionString = "DSN=your_dsn;User ID=your_username;Password=your_password";
For information on configuring a DSN on specific operating systems, see instructions for Windows, macOS, or Linux.
You can establish a connection without a DSN by specifying all necessary parameters directly in the connection string.
$connectionString = "DRIVER=Devart ODBC Driver for MySQL;Server=your_server;Port=your_port;Database=your_database;User ID=your_username;Password=your_password;
For more information, see DSN-less connections.
The following PHP code demonstrates how to connect to MySQL and fetch data using the ODBC driver.
<?php
// Define an ODBC connection string
$connectionString = "your_connection_string";
// Establish the ODBC connection
$connection = odbc_connect($connectionString);
// Check if the connection is successful
if ($connection) {
echo "Connected to MySQL successfully.\n";
// Define a SQL query
$sql = "SELECT actor_id, last_name FROM actor";
// Execute the query
$result = odbc_exec($connection, $sql);
// Check if the query execution was successful
if ($result) {
// Fetch and display the results
echo "Query results:\n";
while ($row = odbc_fetch_array($result)) {
// Print each row of the result set
print_r($row);
}
} else {
echo "Failed to execute query: " . odbc_errormsg($connection) . "\n";
}
// Close the connection
odbc_close($connection);
echo "Connection closed.\n";
} else {
echo "Failed to connect: " . odbc_errormsg() . "\n";
}
?>