PDO while change

The following line of code is completely different to the many others Ive done as I change to PDO, and I’m a little stuck.

while(false !== ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))) {

I tried this, but its not right, I’m not sure

while ($false !== $row->fetch($result)) {


while (($false !== $row)->fetch($result)) { 

This is the error Im getting
Fatal error: Call to a member function fetch() on integer in

Using -

while ($false !== $row->fetch($result)) { 

you don’t need complicated while() structures with PDO …

// setup
$pdo = new PDO( ... );

// query
$stmt = $pdo->query($sql);

foreach ($stmt as $row) {
    // do something with each result row

The only real difference there is sticking the false at the start of the comparison. If I recall correctly, this is sometimes recommended in languages that use a single = sign to assign a value, and a double = sign for comparison, because if you make a typo and use a single = sign you’ll always get an error (as you cannot assign a value to false or true) rather than the alternative.

Ah ok thanks guys, the code below ran, but what is happening now is that the output is duplicated, so everything comes out as needed, but each line is duplicated.

$result = $conn->prepare($query);
  foreach ($result as $row) {

    if(!$flag) {
      fputcsv($out, array_keys($row), ',', '"');
      $flag = true;
	foreach ($row as $key => $value)
    if ($value instanceof DateTime) 
    $row[$key] = date_format($value, 'd/m/y'); 
	$row = str_replace(",", ",", $row);
	$row = str_replace(".", ".", $row);
	$row = str_replace("'", "'", $row);
    fputcsv($out, array_values($row), ',', '"');



That’s because you use PDO::FETCH_BOTH as default fetch mode.

In this line you mean -

$result = $conn->prepare($query, PDO::FETCH_BOTH);

Ye whats happening is that each line in the excel file is duplicating the fields, so you have the fields duplicating next to each other in the same line.

Ah hang on, I missed the post above, so add it in there but in my case its $conn as below

  $result = $conn->prepare($query);

no. I have already shown you in post #2 how to set the fetch mode …

1 Like

Ye sorry Dormilich, i went back and corrected my post as I seen your post too late

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.