4

In the given code I need to print the train-name obtained from query $q1, but in the echo statement I provided this is not working. How do I print the trainname in the given code?

$q1="SELECT st_name FROM tbl_station where st_code='$f'";

$r1=mysql_query($q1);

while($row = mysql_fetch_array($r1)) 

{

$trainname=$r1['st_name'];

}   

$query="SELECT A.train_no AS AA, A.station_id AS AB, A.arrival AS AC, A.dept AS AD, 

B.station_id AS AE, B.arrival AS AF, B.dept AS AG FROM TIME AS A,TIME AS B WHERE A.train_no 

= B.train_no AND A.station_id ='$f' AND B.station_id ='$t'";

$rs=mysql_query($query);

while($row = mysql_fetch_array($rs)) 

{

echo "<tr><td>".$row['AA']."</td> <td>".$trainname."</td> <td>" .$row['AC'] ."</td> 

<td>".$row['AD'] . "</td><td>".$row['AE'] . "</td><td>".$row['AF'] . "</td><td>" 

.$row['AG']. "</td><td>"."<a href='Reservation.php'>Click Me</a><tr><td>";

}
3
  • What does "code is not working" mean? Commented Jan 18, 2014 at 18:01
  • i mean trainname is not printing in second while loop..Is there any way to print trainname in second while loop?? Commented Jan 18, 2014 at 18:07
  • On a side note, this code is insecure, you should look into either mysqli or pdo as a replacement. Commented Jan 18, 2014 at 18:08

3 Answers 3

2

The result row is assigned to the $row variable, not the $r1 variable (which is the query resource):

while($row = mysql_fetch_array($r1)) 
{  
  $trainname=$row['st_name'];   
} 
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way to print trainname in second while loop??
You already do that. It's just initially you were incorrectly assigning a value to the $trainname variable; it should work once you implement the above.
1

You are retrieving data from result object, instead you should fetch data from variable row

while($row = mysql_fetch_array($r1))

    {

    $trainname=$row['st_name'];

    }

Comments

0

There are two issues:

  • mysql_fetch_array gives results that require numeric indexes (This applies to both loops)
    • the fix is either $row = mysql_fetch_array($r1, MYSQL_ASSOC) or $row = mysql_fetch_assoc($r1)
  • you are using the results instead of the row. (This applies to the first loop)
    • the is $trainname=$row['st_name'];

However you have glaring security holes, so you should research mysqli or pdo

1 Comment

mysql_fetch_array without specifying the second parameter returns the row as both a numeric and associative array: array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )

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.