Jump to content

[SOLVED] simple 'while' problem


chocopi

Recommended Posts

I want to get a numerical vaule from my database and change it to a string

 

This is code i came up with, but its not working:

 

while($row = mysql_fetch_array($class))
	 {
	if ( $row['class'] == 1){
	$class = 'A';
	} else
	if ( $row['class'] == 2){
	$class = 'B';
	} else
	if ( $row['class'] == 3){
	$class = 'C';
	}
}
print ("You chose $class \n");

 

Any help would be greatly appreciated,

 

~ Chocopi

Link to comment
https://forums.phpfreaks.com/topic/51336-solved-simple-while-problem/
Share on other sites

Since you are using a while loop I am assuming you are trying to print "You chose $class" for each value from the DB? Why do you have your print outside of the while loop? Change your code to this:

 

<?php

while($row = mysql_fetch_array($class))
	 {
	if ( $row['class'] == 1){
	$class = 'A';
	} else
	if ( $row['class'] == 2){
	$class = 'B';
	} else
	if ( $row['class'] == 3){
	$class = 'C';
	}

             print "You chose". $class ."<br>";
}
?>

 

You're clobbering the variable $class, which is the pointer to the mysql query result, use a different variable.

 

This can be written much more efficiently by using an array:

<?php
$classes = array('','A','B','C');
while($row = mysql_fetch_assoc($class))
	 $cls = $classes[$row['class']];
echo "You chose $cls<br>\n";
?>

 

Ken

 

it was not a problem with the code though, it was because i missed out:

 

<?php
$class = mysql_query("SELECT class FROM users WHERE username='$username'");
?>

 

so obviously no result could be posted because it was not being told where too look  :-[

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.