PDO Query Database ODBC - php

I'm on my way learning about PDO from phpro.org, and a little bit confuse.
<?php
try {
$dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\pdo-tutorial.mdb;Uid=Admin");
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
What is Uid? and what value should I enter?
And, about the query
<?php
try {
$dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\pdo-tutorial.mdb;Uid=Admin");
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM animals";
/*** fetch into an PDOStatement object ***/
$stmt = $dbh->query($sql);
/*** echo number of columns ***/
$result = $stmt->fetch(PDO::FETCH_ASSOC);
/*** loop over the object directly ***/
foreach($result as $key=>$val)
{
echo $key.' - '.$val.'<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I'm using odbc, but why the foreach functions just echo the first row, not looping echoing all my value in the database? here are the result.
Connected to database
ID - 1
animal_type - kookaburra
animal_name - bruce
can you tell me why?

For your second question:
You need to use fetchAll() instead of fetch(), which only gives you one row at a time.
In your code, try:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); (though that will change what your foreach loop looks like).
Alternatively, you can use a while loop to fetch each row as you need it:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//Do something with $row
}

Uid is Username with which you want to connect to database, if your mdb file is not protected you may omit this parameter.
To fetch all results you have to use fetchAll (http://php.net/manual/en/pdostatement.fetchall.php).

Related

PDO row count - num_rows equivalent

I'm moving PHP code from mysql to ms sql server.
This will execute my query:
$r = $db_conn->prepare($sql);
$r->execute();
Before I start processing, I need to count how many rows were returned.
old code:
$r->num_rows;
new code:
$rows = $r->fetchAll(PDO::FETCH_ASSOC);
$rcount = count($rows);
All good, but when I try to access values from 1st row I'm getting nothing...
try {
$row = $r->fetch(PDO::FETCH_ASSOC);
} catch (Exception $ex) {
return 0;
}
I need to repoint to 1st row in my recordset after doing the count, how can I do this without having to requery the database again?
I'm new to PHP, sorry for dumb and probably obvious question.
Thanks in advance.
There isn't a way in PDO to reset the pointer. You could execute the query again, but given that you've already fetched all the data with your call to fetchAll, that is wasteful. Instead, to access the data, simply loop over the $rows array e.g.
foreach ($rows as $row) {
// do something
}
Note that if you expect an exception on fetch, it is likely you might get one on fetchAll too, so you should wrap the call to fetchAll in a try/catch block:
try {
$rows = $r->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $ex) {
return 0;
}
One possible approach, if you use PHP Driver for SQL Server, is to use PDOStatement::rowCount and client-side cursor. With this type of cursor row count is available after a query is executed, but this type of cursor should be used for small (medium) result sets.
<?php
# Connection
$server = 'server\instance,port';
$database = 'master';
$uid = 'uid';
$pwd = 'pwd';
# PDO Connection
try {
# SQL authentication
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
# Windows authentication
#$conn = new PDO("sqlsrv:server=$server;Database=$database");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
# Client-side cursor
try {
$options = array(
PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL,
PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED
);
$stmt = $conn->prepare("SELECT * FROM master.sys.server_principals", $options);
$stmt->execute();
echo 'Row count: '.$stmt->rowCount().'<br>';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC) ){
echo 'Login name: '.$row['name'].'<br>';
}
} catch( PDOException $e ) {
die( "Error executing query".$e->getMessage() );
}
# End
$stmt = null;
$conn = null;
?>

How can I fetch data from database using this prepare statement

//this is my connection function. It is connecting databse successfully when I check.
$conn = connection($config['servername'],$config['username'],$config['password']);
after this I Used following code to fetch data from Database
$id = 2;
if($conn) {
try {
$stmt = $conn->prepare('SELECT * FROM customer_tbl WHERE cus_id = :id');
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt->bindParam(':id', $id);
$results = $stmt->execute();
}catch (PDOException $e){
echo 'Error: ' . $e->getMessage();
}
}
this code showing following error message on the browser
Error: SQLSTATE[IM001]: Driver does not support this function: This driver doesn't support setting attributes
what's wrong with my code?. Why I could not fetch data's from database?
if I want to fetch this specified data from databese using prepare statement
how to code?
Add the following
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
after the connection string with $conn Object
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
To fetch data use
$stmt->execute();
$rows= $stmt->fetch(PDO::FETCH_ASSOC);
print_r($rows); // to print an array
it will return data in associative array format.
PDO provides various fetch options look here

How to wite PHP code with the following SQL query?

I am trying to query out a result, it works in SQL query, but I'm trying to get the result using PHP
SELECT prs_amtdb FROM `prs` WHERE prs_amtcrck = 0
Using mysqli
Note: Make sure you bind your value. mysqli does not automatically
secure your query
$connection= mysqli_connect($host, $user, $password, $database);
$query="SELECT prs_amtdb FROM prs WHERE prs_amtcrck = 0";
$result= mysqli_query($connection, $query);//$connection is your database
//connection
//fetch the result
while($row= mysqli_fetch_array($result)){
echo $row['column_name'].'<br/>';
}
Using PDO:
$query = $db->query("SELECT `prs_amtdb` FROM prs WHERE `prs_amtcrck` = 0");
$results = $query->fetchAll();
foreach($results as $result) {
echo $result;
}
http://php.net/manual/en/pdo.query.php
If you have user input that you're using in your query you should always use prepared statements eg:
$query = $db->prepare("SELECT `prs_amtdb` FROM prs WHERE `prs_amtcrck` = :atmcrck");
$query->bindParam(':atmcrck', 0); // 0 will be the user input
$query->execute();
$results = $query->fetchAll();
foreach($results as $result) {
echo $result;
}
Make sure you have a database connection setup in PDO:
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
die($e->getMessage());
}
http://php.net/manual/en/pdo.connections.php

Amfphp Service Browser Not Displaying MySQL Result

I am developing my first project using Amfphp and am writing my first simple Service. Here is my getData method:
public function getData() {
// Connect to the database using PHP Data Objects (PDO).
try {
$pdo = new PDO('mysql:host=localhost;port=8889;dbname=amf_test', 'root', 'root');
} catch (PDOException $e) {
print "Connection Error!: " . $e->getMessage() . "<br/>";
die();
}
// Set an Error Handling mode.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully\n";
// Retrieve all rows.
$tsql = 'SELECT * FROM authors_aut';
$stmt = $pdo->prepare($tsql);
$stmt->execute();
// Echo the SQL Error Code
echo "SQL Error code: " . $pdo->errorCode() . "\n";
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$row_count = $stmt->rowCount();
echo $row_count.' rows selected' . "\n";
foreach ($pdo->query($tsql) AS $row) {
$id_aut = $row['id_aut'];
$fname_aut = $row['fname_aut'];
printf("Data: %s (%s) <br />", $id_aut, $fname_aut);
}
// Close the database connection
$stmt = null;
$dbh = null;
// Return the array.
return $results;
}
When I go to the Amfphp Back Office Service Browser, select my getData method and call it I get my comments but no data. Before I added my echo and printf lines I didn't the Service Browser returned nothing leaving me thinking my Service was not working (it still may not be!). My comments appear to show that I have successfully selected the data from the MySQL database but is it being returned?
I welcome your thoughts.
Chris

PDO mySql Connection

There is a link that I found a while back. What I would like to know is:
How do I query a simple SELECT * FROM table_name using PDO?
I tried playing around with the examples here but I was not getting any results back. All along I have been using the mysql_connect method which I dont want to use anymore. I would like to use following:
<?php
$host="127.0.0.1"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="microict-intrasys"; // Database name //
//$id = 5;
try {
$conn = new PDO('mysql:$host;$db_name,', $username, $password);
$stmt = $conn->prepare('SELECT version FROM system_info');
// $stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) )
{
foreach($result as $row)
{
print_r($row);
}
}
else
{
echo "No rows returned.";
}
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>
First create the pdo instance and connect...
$db = new PDO('mysql:host=127.0.0.1;dbname=yourDBName;charset=utf8', 'username', 'password');
I use charset as well to have the correct formated data here... but you dont have to use it. Connection string could also look like
PDO("mysql:host=127.0.0.1;dbname=yourDBName" , $username, $password);
(using $username & $password here)
since working with pdo i ran into speed issues when i use localhost instead of 127.0.0.1 PDO seems to use the DNS to translate localhost into 127.0.0.1 and this causes speed. And im talking about seconds just for connecting to DBs
after connecting you can query like
$stmt = $db->query("SELECT * FROM table");
and than fetch could results like
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'].' '.$row['field2']; //etc...
}
or
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
so than you should have at least some result.... (simple way)
I guess your problem is...
accourdig to your source you have a issue in your connectionstring....
<?php
$host="127.0.0.1"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="microict-intrasys"; // Database name
//$id = 5;
try {
$conn = new PDO('mysql:host={$host};dbname={$db_name}', $username, $password);
// you neeeeeed this--^ and this--^
$stmt = $conn->prepare('SELECT version FROM system_info');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) )
{
foreach($result as $row)
{
print_r($row);
}
}
else
{
echo "No rows returned.";
}
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>
you are missing some in your connection string! kinda typo
your parsed string looks like
"mysql:localhost;microict-intrasys"
and thats wrong. it must look like
//"mysql:host=localhost;dbname=microict-intrasys"
"mysql:host=127.0.0.1;dbname=microict-intrasys" // better
PDO Check
if (!defined('PDO::ATTR_DRIVER_NAME')) {
echo 'PDO unavailable';
}

Categories