What is the PDO equivalent to sqlsrv_query and sqlsrv_fetch_array?

I'm new to PHP and I need to convert two lines of code from sqlsrv to pdo but I do not know the commands or syntax. The code is as follows:

$result = sqlsrv_query($conn,$checkTable);
$data = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC);

Open in new window

What is the PDO equivalent?
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
PDO is object oriented, so you would need to create a connection object:

$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);

For the query, you would then call query() on the connection, which would return a PDO statement object:

$stmt  = $dbh->query($checkTable);

And then you'd call fetch() on the statement (in a loop if you have more than record / on it's own if you know you'll only have one)

while ($row = $stmt->fetch()):

You can pass an argument into the fetch() method to tell it whether to fetch an array, an object, a class etc. For an array (similiar to sqlsrv_fetch_array), you can either rely on the default by not passing in an argument, or you can specifically ask for an associated array:

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)):

If you want objects instead of arrays, then use

while ($row = $stmt->fetch(PDO::FETCH_OBJ)):

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
JeffDeveloperAuthor Commented:
Worked perfectly. Thank you Chris.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.