0

Hey I'm running php mysqli query:

<?php do { echo $row['depicao']; ?>-<?php } while ($row = mysqli_fetch_array($query)); ?>

The result I need should show the following

data-data2-data3-data4 etc.

However what I'm seeing is:

-data-data2-data3-data4

how can I get the "-" to not appear as the first result?

Ive tried this but I get the same result.

<?php do { echo $row['depicao']; echo'-'; ?><?php } while ($row = mysqli_fetch_array($query)); ?>

Thanks

2
  • In first iteration of do $row is not defined Commented Jun 10, 2017 at 10:27
  • ?? The query runs fine, it just doesn't show the results in the desired order. Commented Jun 10, 2017 at 10:32

3 Answers 3

1

In

do { echo $row['depicao']; ?>-<?php } 
while ($row = mysqli_fetch_array($query))

$row gets defined after first iteration, and not before. That's why $row['depicao'] outputs nothing. If you had error_reporting on - you would also see a notice.

So, first fix is to define $row first and then output it:

while ($row = mysqli_fetch_array($query)) {
    echo $row['depicao']; 
    echo '-';
}

But in this case your output will be ended with -.

So, one of the solutions is to collect values in array and implode'em:

$values = [];
while ($row = mysqli_fetch_array($query)) {
    $values[] = $row['depicao']; 
}
echo implode('-', $values);
Sign up to request clarification or add additional context in comments.

Comments

0

Use while loop instead of do...while

Because when you use do while loop it'll execute once always and then it'll check the condition and that's why you got the - at very first of your result.

So use while loop to check the condition, if true then code under loop will execute otherwise not.

I'll strictly recommend you to learn about loops.

Comments

0

Try using while loop instead of do-while.

<?php while($row = mysqli_fetch_array($query)) { echo $row['depicao'];echo'-';} ?>

The problem with do while is that it executes at least once even if the condition fails. Hence one "-" is printed in beginning even without evaluating the condition.

If the goal is just to remove the extra "-" then it can be done with-

<?php do { echo $row['depicao']; if($row['depicao']!=null) echo "-"; } while ($row = mysqli_fetch_array($query)); ?>

3 Comments

That fixed it. Many Thanks!
Still you have a "-" at the end
Okay. my bad. If the goal is just to remove extra "-" then it can be done with- <?php do { echo $row['depicao']; if($row['depicao'] != null) echo "-"; } while ($row = mysqli_fetch_array($query)); ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.