3

I am trying to echo some text if my loop returns with no data but can't get it do work. I have tried a few things but no luck.

my code:

$result = mysql_send("SELECT * FROM datatable WHERE id='".
    $_SESSION['id']."'ORDER BY id ASC LIMIT 2");

while($row=mysql_fetch_array($result)) {
    $a = 1;
    extract($row);

    echo 'Trans ID: ';
    echo $row['trans_id'];
    echo '<br>';
    echo 'Amount: ';
    echo $row['amount'];
    echo '&nbsp;';
    echo $row['euros'];
    echo '<br>';
    echo '<br>';
}


if ($a = 1) {
    echo 'No History';
} else {
    echo '<a href="#">View history</a>';
};

Can Anyone help me with how to do if statements on a loop`?

1
  • 1
    Artefacto kindly reformatted your code, but in future please ensure your code is correctly indented and formatted. This makes it easier for yourself and others to read the code. Commented Jun 18, 2010 at 13:39

4 Answers 4

2

You have an assignment, which returns the result of the assignment (i.e. 1)

if ($a = 1) {

instead of a comparison, which is what you probably want:

if ($a == 1) {

Therefore, "No history" will always be echoed.

Sign up to request clarification or add additional context in comments.

Comments

2

use mysql_num_rows(); it will tell you if you have any results from query

$result = mysql_send("SELECT * FROM datatable WHERE id='".
$_SESSION['id']."'ORDER BY id ASC LIMIT 2");

$count = mysql_fetch_array($result);

if($count > 0) {
    while($row=mysql_fetch_array($result)) {
        # your code
    }
}

# NOTE THE == not =
if ($a == 1) {
    echo 'No History';
} else {
    echo '<a href="#">View history</a>';
};

You will also have issue with your if statement as youu are using assigment rather than comparison: $a = 1 will set $a = 1 and $a == 1 will check of it equals 1

Comments

1

if($a == 1) ....

Comments

0

== is a comparison, = is an assignment.

Change to

if ($a == 1) {

Comments

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.