0

When selecting and displaying records using php's PDO and MySql, how can I print one row once and loop through the rest? In the code below, I need to print $row['parentName'] only once, and loop through all the other row. What is an efficient way to do it? The way I'm doing it does not work and I get Notice: Undefined variable: row in C:\web\apache\htdocs\index.php on line 227.

I don't mind taking a whole new approach, since this isn't implemented yet.

$stmt = $conn->prepare($sql); $stmt->execute($thisArray); $rows = $stmt->rowCount(); if($rows >= 1) { echo '<div>'.$row['parentName'].'</div>'; //Echo only once. while($row = $stmt->fetch()) { echo '<div>'.$row['childName'].'</div>'; } } else { echo 'We could not find anything to display.'; } 

EDIT I'm stuck at the fetch part.

1
  • You have $rows->$rows = $stmt->rowCount(); but are trying to use $row->$row['parentName']. You could move echo '<div>'.$row['parentName'].'</div>'; inside your while loop and use a counter to only print when counter is 0. Commented Oct 14, 2013 at 14:08

1 Answer 1

1

Try this:

$stmt = $conn->prepare($sql); $stmt->execute($thisArray); if ($stmt->rowCount() >= 1) { $array = $stmt->fetchAll(); echo '<div>', $array[0]['parentName'], '</div>'; foreach ($array as $row) { echo '<div>', $row['childName'], '</div>'; } } else { echo 'We could not find anything to display.'; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.