Solved

Making a dsn-less connection to a Microsoft Access Database

Posted on 2006-06-25
22
323 Views
Last Modified: 2013-12-12
I need the details (with examples) of how to connect to a Microsoft Access database from php with a dsn-less connection.

Also sample of how to execute SQL ("Select * from table_name") and how to handle the result set.

In other words, the equivalent of:

$Host = "sqlc0e.megasqlservers.com";
$User = "some_user";
$Password = "some_pwd";
$DBName = "some_database";
$TableName = "schedule";

$Link = mysql_connect ($Host, $User, $Password);

$Query = "SELECT * from $TableName where date = '" . $thedate . "' order by AMPM";

$result = mysql_db_query ($DBName, $Query, $Link);

$ns = mysql_num_rows ($result);

for($i = 0; $i , $ns $i++) {
    $row = mysql_fetch_row ($result);
// do something with data

}

Thanks,

rkorts
0
Comment
Question by:Richard Korts
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 8
  • 4
  • +1
22 Comments
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 16981238
code sample with dsn:
http://www.w3schools.com/php/php_db_odbc.asp

connection sample without dsn:
$db_connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("Crafta.mdb") ." ;DefaultDir=". realpath(".");
0
 
LVL 8

Expert Comment

by:hiteshgupta1
ID: 16981867
$db=realpath("YOURDB.mdb");
$conn=new COM('ADODB.Connection');
$conn->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=$db");

$sql="SELECT * from YOUTTBL";
$rs=$conn->Execute($sql);

while (!$rs->EOF){
     echo $rs->Fields["FIELD"]->Value."<br>";
     $rs->MoveNext();
}
$rs->Close();
$conn->Close();
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 16981983
I've seen the ADODB answer a LOT of the times when people want to use MS Access and PHP.

When using ODBC, you need to load the MS Access ODBC driver (The DSN shown by AngelIII is entirely suitable - more reading at http://www.carlprothman.net/Default.aspx?tabid=90#ODBCDriverForAccess).

Is there any performance differential between using ODBC and COM for MS Access?

0
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 

Author Comment

by:Richard Korts
ID: 16988002
To hiteshgupta1,

I tried your approach. It does not work. The following is an EXACT COPY of the php file. It produces ONLY "FullName field from Access" in the browser output.

Note, I put the print's in to try to see what was going wrong. They don't even produce anything.

What's wrong?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
      <title>Test Access from php</title>
</head>

<body>
FullName field from Access
<?php
$db=realpath("lss.mdb");
$conn=new COM('ADODB.Connection');
$conn->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=$db");
print("Returned conn = $conn<br>\n");
$sql="SELECT * from customer";
$rs=$conn->Execute($sql);
print("Returned rs = $rs<br>\n");
while (!$rs->EOF){
     echo $rs->Fields["FullName"]->Value."<br>";
     $rs->MoveNext();
}
$rs->Close();
$conn->Close();
?>

</body>
</html>
0
 

Author Comment

by:Richard Korts
ID: 16988025
To angelIII

I tried your approach. It does not work. The following is an EXACT COPY of the php file. It produces ONLY "FullName field " in the browser output.

Note I put the print in to try to see what's going on & it fails too.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
      <title>Test Access 2nd try</title>
</head>

<body>
<?php
print("FullName field\n");
$conn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("lss.mdb") ." ;DefaultDir=". realpath(".");
print("conn result: $conn\n");
$sql="SELECT * FROM customer";
$rs=odbc_exec($conn,$sql);
while (odbc_fetch_row($rs)) {
      $name=odbc_result($rs,"FullName");
      print("name = $name\n");
}      
?>
</body>
</html>
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 16989875
>It produces ONLY "FullName field " in the browser output.
well, I assume the values for all records for that field?
in that case, it works perfectly, the only thing you have to do is to add more lines:

     $name=odbc_result($rs,"FullName");
     $otherfield=odbc_result($rs,"otherfield");
    etc

and print them out as required...
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 16990539
<?php
// Define the ODBC Connection string.
$s_conn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("lss.mdb") ." ;DefaultDir=". realpath(".");

// Connect to the ODBC Data source and return an ODBC Connection Resource.
$r_conn = odbc_pconnect($s_conn, '', ''); // More on the pconnect right after this broadcast.

// Define the SQL Statement to be used.
$s_SQL = 'SELECT * FROM customer';

// Execute the query and get a results set resource.
$r_results = odbc_exec($r_conn, $s_SQL);

// Build the output.
$s_output = '';
$s_keys = NULL;
$i_count = 0;
while (False !== ($a_row = odbc_fetch_array($r_results)))
      {
      if (is_null($a_keys))
            {
            $s_keys = '<tr><th>#</th><th>' . implode('</th><th>', array_keys($a_row)) . '</th></tr>';
            }
      $s_output = '<tr><th>' . ++$i_count . '</th><td>' . implode('</td><td>', $a_row) . '</td></tr>';
      }

// Output the entire results.
echo <<< END_HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
     <title>Test Access 2nd try</title>
</head>
<body>
<table border="1">
      <thead>
      {$s_keys}
      </thead>
      <tbody>
      $s_output
      </tbody>
</table>
</body>
</html>
END_HTML;
?>
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 16990553
Idiot!!!!

$s_output = '<tr><th>' . ++$i_count . '</th><td>' . implode('</td><td>', $a_row) . '</td></tr>';

should be ...

$s_output .= '<tr><th>' . ++$i_count . '</th><td>' . implode('</td><td>', $a_row) . '</td></tr>';

.= and not =

Append not assign.
0
 

Author Comment

by:Richard Korts
ID: 16993594
To angelIII,

I did not make myself clear.

The php file above produces the EXACT html for the browser, as follows.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
     <title>Test Access 2nd try</title>
</head>

<body>
FullName field
conn result: DRIVER={Microsoft Access Driver (*.mdb)}; DBQ= ;DefaultDir=/services4/webpages/r/k/rkassociates.com/public/LSS


In other words, the php lines after print("conn result: $conn\n"); produce NOTHING. Note that even the </body> and </html> that are AFTER the ?> are missing.

I've never seen anything this strange in thousands of php pages I've written.

Any clues from ANY of you will be MOST appreciated. I'd say this behavior borders on the impossible.
0
 

Author Comment

by:Richard Korts
ID: 16994569
To RQuadling,

I tried your script. Apparently it has a php error. See this link. Following the link is the ACTUAL SOURCE as I have it.

http://www.rkassociates.com/LSS/RQuadling.php

<?php
// Define the ODBC Connection string.
$s_conn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("lss.mdb") ." ;DefaultDir=". realpath(".");

// Connect to the ODBC Data source and return an ODBC Connection Resource.
$r_conn = odbc_pconnect($s_conn, '', ''); // More on the pconnect right after this broadcast.

// Define the SQL Statement to be used.
$s_SQL = 'SELECT * FROM customer';

// Execute the query and get a results set resource.
$r_results = odbc_exec($r_conn, $s_SQL);

// Build the output.
$s_output = '';
$s_keys = NULL;
$i_count = 0;
while (False !== ($a_row = odbc_fetch_array($r_results)))
     {
     if (is_null($a_keys))
          {
          $s_keys = '<tr><th>#</th><th>' . implode('</th><th>', array_keys($a_row)) . '</th></tr>';
          }
            $s_output .= '<tr><th>' . ++$i_count . '</th><td>' . implode('</td><td>', $a_row) . '</td></tr>';
     }

// Output the entire results.
echo <<< END_HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
     <title>Test Access 2nd try</title>
</head>
<body>
<table border="1">
     <thead>
     {$s_keys}
     </thead>
     <tbody>
     $s_output
     </tbody>
</table>
</body>
</html>
END_HTML;
?>

Any suggestions?

rkorts
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 16995590
>To angelIII,
>I did not make myself clear.
Indeed, I did not understand it like that, now it is clear.

Now, you have to "debug" what is happening. put a line print "debug xy"; in between all the statements, to find out which one is actually making the php quit.

do you have any entries in the apache log (ie is the logging configured properly)
0
 

Author Comment

by:Richard Korts
ID: 16995797
To angelIII:

I turned on some error stuff. It says this:

Fatal error: Call to undefined function: odbc_exec() in /services4/webpages/r/k/rkassociates.com/public/LSS/access_test.php on line 17

Does something have to be configured in php.ini or ???

Thanks
0
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
ID: 16995881
well, this look like we will get somewhere.

check this page for the php.ini settings:
http://lu2.php.net/manual/en/ref.uodbc.php


also, I don't see a odbc_connect() anywhere:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
     <title>Test Access 2nd try</title>
</head>

<body>
<?php
print("FullName field\n");
$conn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("lss.mdb") ." ;DefaultDir=". realpath(".");
$db = odbc_connect($conn,'','');
print("conn result: $conn  ($db)\n");
$sql="SELECT * FROM customer";
$rs=odbc_exec($db,$sql);
while (odbc_fetch_row($rs)) {
     $name=odbc_result($rs,"FullName");
     print("name = $name\n");
}    
?>
</body>
</html>

0
 

Author Comment

by:Richard Korts
ID: 16996249
To angelIII:

I added the odbc_connect function per your code above. It produces this.

FullName field
Fatal error: Call to undefined function: odbc_connect() in /services4/webpages/r/k/rkassociates.com/public/LSS/access_test.php on line 15

My take on this is that the various odbc_*** functions ARE NOT available. It's not clear from the link you gave me what settings should be used / not used in php.ini. If I could get that info, then I could get my host to configure it properly.

Thanks
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 16996381
can you run the function phpinfo() on a test page, and check if the odbc section is displayed resp. what odbc settings you have. looks like it is not activated.


I see you opened a new question for that:
http://www.experts-exchange.com/Web/Web_Languages/PHP/Q_21901223.html
0
 

Author Comment

by:Richard Korts
ID: 16996613
To angelIII:

It contains NOTHING about odbc. How should it be modified?

http://www.rkassociates.com/LSS/phpinfo.php
0
 

Author Comment

by:Richard Korts
ID: 16996665
To angelIII:

Note that I awarded you the points on this one even though it is not solved.

I appreciate your continuing efforts to help.

The first answer to my "new" question points to something I already found that is of no value to me. Those kind of "put a link in as the answer" will NEVER get awarded points from me on Experts Exchange.

I have to communicate to my web host (who is largely NOT technical) how to set the php.ini settings in such a way as to make this work.

Thanks,

rkorts
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 16996688
check out in the php.ini file if you have a line containing extention=php_odbc.dll
I guess it is commented out (or not present at all).
ensure it is there and not commented, and try again
0
 

Author Comment

by:Richard Korts
ID: 16996790
To angelIII:

I searched the page that results from phpinfo() for the letters "odbc" which ARE NOT on that page.

I have a call into my web host asking them to configure php.ini to enable odbc but they probably won't know what I'm talking about unless I tell them PRECISELY what parameters to set what way.
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 16998553
as I said:
extention=php_odbc.dll
needs to be in the php.ini file (on windows platform)
extention=odbc.so
needs to be in the php.ini file (on *nix platform)


0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 16999235
ODBC is now built into the windows version. No external DLL needed. Has been for a LONG time!

And the link you gave has no output at all! Very strange
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 16999261
the phpinfo returned 4.1.1, so I guess odbc was not built-in yet
0

Featured Post

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question