0

here is my code, all is fine i am able to print the values fetched from the database using a while block. but i am unable to assign the values to another variable.

<?php

     //all the code to connect etc

     while($row=mysql_fetch_array($result)){
         echo "<tr>";
         echo "<td>" . $id++ . "</td>";
         echo "<td>" . $row['firstname'] . "</td>";
         echo "<td>" . $row['lastname'] . "</td>";
         echo "</tr>";
     }

     while($row=mysql_fetch_array($result)){
         $compname=$row['firstname'];
         $contname=$row['lastname'];
         $contmail=$row['email'];
         $cont=$row['domain'];
    }
?>
Richard
  • 8,961
  • 3
  • 38
  • 47
supersayan
  • 13
  • 5

1 Answers1

0
while($row=mysql_fetch_array($result)){

  $compname[]=$row['firstname'];
  $contname[]=$row['lastname'];
  $contmail[]=$row['email'];
  $cont[]=$row['domain'];
}

all the variable will be arrays (specifically array items) with their respective values.

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

edit #1

i will suggest this:

while($row=mysql_fetch_array($result)){

$compname[]=$row['firstname'];
$contname[]=$row['lastname'];
$contmail[]=$row['email'];
$cont[]=$row['domain'];

echo "<tr>";
 echo "<td>" . $id++ . "</td>";
  echo "<td>" . $row['firstname'] . "</td>";
  echo "<td>" . $row['lastname'] . "</td>";

 echo "</tr>";
}

edit #2

for eching the items,

foreach($cont as $i => $v)
{
    echo $v.'<br/>';
}
Community
  • 1
  • 1
itachi
  • 6,323
  • 3
  • 30
  • 40
  • ok ill use msqli :) n try. now if i want to use this left side var for another query or simply echo how should i? echo $cont; or echo cont[]; ? – supersayan Nov 16 '14 at 15:21
  • suppose i remove the while as i am sure i only have one row in my db. then what chenges woould be suggested? :) – supersayan Nov 16 '14 at 15:23
  • i dont want arrray variables in the first place. suppose i dont use while to fetch multiple rows. As i have only one row as output to my query. is Key value pair something possible? – supersayan Nov 16 '14 at 15:29
  • what if you will have more than one row in future? you will change your code? – itachi Nov 16 '14 at 15:32
  • well my application always requires just one row:) i plan to insert these row variable into another table, with a few changes – supersayan Nov 17 '14 at 04:32
  • i don't see what is the problem with arrays. even if it is one row, it will be in the array you can access it. – itachi Nov 17 '14 at 04:42