Jump to content

[SOLVED] while loops with SUBSTRING_INDEX problem


java12

Recommended Posts

From the field 'division', I'm trying to take the number to the left and divide it by the number to the right of a "/" and then add 1 each time a condition is met. So that 10/1 = 11 and 5/2 = 3.5 whenever field_id=9 etc.

 

The code below (when without the while loops) works for a single row. But I'm new to PHP and cannot get it to loop correctly without outputing the right number against every left number in the division field, so 6 rows outputs 36 results instead of just 6 results.

 

Also, can it be done with a single SELECT statement? Any help would be appreciated.

...
$result = mysql_query("SELECT field_id FROM table1 WHERE field_id=9");
      while ($table = mysql_fetch_array($result))     {
$sql = mysql_query("SELECT SUBSTRING_INDEX(division,'/',1) AS numleft FROM table1 WHERE field_id=9");
      while ($row = mysql_fetch_query($sql))         {
$sql2 = mysql_query("SELECT SUBSTRING_INDEX(division,'/',-1) AS numright FROM table1 WHERE field_id=9");
      while ($row2 = mysql_fetch_array($sql2))      {
$sql3 = ($row[numleft]/$row2[numright])+1;
      echo "$sql3";
}
}
}
....

PHP 5.2 MySQL 5.0.27

try

<?php
$result = mysql_query("SELECT division FROM table1 WHERE field_id = 9");
while ($row = mysql_fetch_row($result)) {
    list($numleft, $numright) = explode('/', $row[0]);
    $val = 1 + $numleft / $numright;
    echo $val, '<br>';
}
?>

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.