无法分配使用php获取的变量

时间:2014-11-16 15:17:22

标签: php mysql

这是我的代码,一切都很好我可以使用while块打印从数据库中获取的值。但我无法将值分配给另一个变量。

<?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'];
    }
?>

1 个答案:

答案 0 :(得分:0)

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

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

所有变量都是数组(特别是数组项)及其各自的值。

  

Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

编辑#1

我会建议:

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>";
}

编辑#2

用于挖掘物品,

foreach($cont as $i => $v)
{
    echo $v.'<br/>';
}