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?
LVL 1
JeffDeveloperAsked:
Who is Participating?
 
Chris StanyonConnect With a Mentor Commented:
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()):
    var_dump($row);
endwhile;

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)):
0
 
JeffDeveloperAuthor Commented:
Worked perfectly. Thank you Chris.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.