LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Variables in PHP/MySQL (https://www.linuxquestions.org/questions/programming-9/variables-in-php-mysql-704982/)

win32sux 02-16-2009 03:19 AM

Variables in PHP/MySQL
 
Let's say I have something like this:
PHP Code:

while($row mysql_fetch_array($Query))
   {
      
$Foo $Bar;
   } 

Furthermore, let's say that I want $Foo to end up with the product of the multiplication of two fields in the row, Price and Quantity. I could do this by replacing $Bar like:
PHP Code:

while($row mysql_fetch_array($Query))
   {
      
$Foo $row['Price']*$row['Quantity'];
   } 

However, due to some weird coding I did a while back, I am currently in a situation where I need for this computation (not the product) to be stored in $Bar outside the while loop, and then have $Foo end up with the product of the computation when being assigned the value of $Bar. I can't figure out how to do this and would really appreciate your help.

I've tried doing it like:
PHP Code:

$Bar "\$row['Price']*\$row['Quantity']";

while(
$row mysql_fetch_array($Query))
   {
      
$Foo $Bar;
   } 

But $Foo ends up with the text of my intended computation, instead of the product being computed inside the loop.

rsciw 02-16-2009 04:48 AM

What's wrong with the 2nd of the three code blocks?
if the coding is weird, it calls for a recoding ;)

you are effectively defining $bar as a variable containing a string, and then assigning that
string to $foo

therefore you'll end up with
$foo == "\$row['Price']*\$row['Quantity']" every time.

might be doable with
sprintf
havn't tried that yet though in a circumstance like this O_o

overall it looks rather weird, as you say, and not neat.
Best way would be to do it like in the 2nd code block (where btw $foo gets overwritten every time if there's more than one data row, unless it's intended)

win32sux 02-16-2009 04:55 AM

Quote:

Originally Posted by rsciw (Post 3445253)
What's wrong with the 2nd of the three code blocks?
if the coding is weird, it calls for a recoding ;)

you are effectively defining $bar as a variable containing a string, and then assigning that
string to $foo

therefore you'll end up with
$foo == "\$row['Price']*\$row['Quantity']" every time.

might be doable with
sprintf
havn't tried that yet though in a circumstance like this O_o

overall it looks rather weird, as you say, and not neat.
Best way would be to do it like in the 2nd code block (where btw $foo gets overwritten every time if there's more than one data row, unless it's intended)

Yeah, I think you're absolutely right. The best option really is to rewrite this chunk of code in such a manner that this kind of weirdness is no longer necessary. I think I'll do that. Thanks man. :)

rsciw 02-16-2009 04:59 AM

yw :)


All times are GMT -5. The time now is 02:10 PM.