Home >Backend Development >PHP Tutorial >How to access database through ODBC in PHP_PHP Tutorial
Environment used
First create a database for testing
Then create an ODBC connection
Then create a PHP Script for testing
Let’s test it
Environment used
This document is mainly explained in the Win32 environment. What you need is a computer running Windows 9x/NT/2000, with any kind of web server and PHP3 or PHP4 installed, and can correctly execute PHP Script. And there is a The above SQL database software, for example: Access...
This document uses the MS-Access database for illustration. Other databases can be connected to ODBC in a similar way.
First create a database for testing
Enter MS-Access and create an odbctest.mdb file.
Start creating a data table.
We give it two data tables Fields: id and name.
Name this data table Class.
Then we enter some data. For example:
Then create an ODBC connection
Open the "ODBC Data Source" in the console.
Select the "System Data Source Name" page.
Click the "Add..." button.
Select the ODBC driver you want to use. Please select "Microsoft Access Driver" here, of course if If you use other databases, select the ODBC Driver of the database.
Click the "Finish" button.
This window will appear for further settings.
Enter the data source name as "WebDB". You can enter the description part as you like, and you can understand it yourself.
Click the "Select..." button and enter the location of the database file you want to connect. For example: c:odbctest.mdb here
Then click the "Advanced..." button. This screen will appear:
The parts you need to enter are: login name and password, here we first set them to 'webuser' and 'webpassword' respectively.
OK. The ODBC setting part has been completed.
Create a PHP Script for testing
The following is the content of a PHP Script for testing. Please save it, for example, to the file root of your web server. Directory.
function Error_Handler( $msg, $cnx )
{
echo "$msg n";
// To avoid occupying the link, close it before the end of the program is very important.
odbc_close( $cnx);
exit();
}
// Establish an ODBC connection and pass it back to $cnx
$cnx = odbc_connect ('WebDB', 'webuser', 'webpassword');
// If there are permission issues during testing, maybe you can use superadmin to access:
// $cnx = odbc_connect( 'WebDB' , [sa login] , [sa password] );
if( ! $cnx ) {
Error_handler( "An error occurred in odbc_connect" , $cnx );
}
// Send a simple odbc query. Return an odbc indicator
$cur= odbc_exec( $cnx, "select id,name from Class" );
if( ! $cur ) {
Error_handler( "An error occurred in odbc_exec (no indicator returned) " , $cnx );
}
echo "
Name | |
---|---|
Total $num_row people |