循环变量并分配值

时间:2013-09-02 13:23:40

标签: php

我有一个包含20行和10列的表单,元素ID由_r1,_r2等区分,而不是从我的查询手动分配所有值,我希望循环遍历它们。

这样的东西
//Set all mileage fields to empty
for ($i = 1; $i <= 20; $i++) {
    $strTravelDate_r.$i = "";
    $strHBE_r.$i = "";
    $strPassenger_r.$i = "";
    $strCongestionCode_r.$i = "";
    $strTravelReason_r.$i = "";
    $strAddress1_r.$i = "";
    $strAddress2_r.$i = "";
    $strDistance_r.$i = "";
    $strRate_r.$i = "";
    $strLineAmount_r.$i = "";
}

//Get mileage claims
$sql_miles = 'SELECT * FROM `tblsaved_mileage` WHERE `strUsername`="'.addslashes($username).'"';
$rs_miles = mysql_query($sql_miles);
$count_miles = mysql_num_rows($rs_miles);
$i = 1;
if ($count_miles > 0) {
    while ($row_miles = mysql_fetch_array($rs_miles)) {
        $strTravelDate_r.$i = $row_miles['strTravelDate'];
        $strHBE_r.$i = $row_miles['strHBE'];
        $strPassenger_r.$i = $row_miles['strPassenger'];
        $strCongestionCode_r.$i = $row_miles['strCongestionCode'];
        $strTravelReason_r.$i = $row_miles['strTravelReason'];
        $strAddress1_r.$i = $row_miles['strAddress1'];
        $strAddress2_r.$i = $row_miles['strAddress2'];
        $strDistance_r.$i = $row_miles['strDistance'];
        $strRate_r.$i = $row_miles['strRate'];
        $strLineAmount_r.$i = $row_miles['strAmount'];

        $i = $i + 1;
    }
}

但我得到了一大堆

Notice: Undefined variable: strTravelDate_r in ........

Notice: Undefined variable: strHBE_r in ........

Notice: Undefined variable: strPassenger_r in ........

2 个答案:

答案 0 :(得分:2)

使用数组,而不是变量:

$results = array();
while ($row_miles = mysql_fetch_assoc($rs_miles)) {
    $results[] = $row_miles;
}

现在您可以访问$results[$i]['strTravelDate'],例如。

答案 1 :(得分:0)

从MySQL库的选择(现在过时的扩展)到分配变量的方式,你的方法是完全错误的。您为此目的使用数组。此外,如果您使用PDO - 您创建的所有内容都会变为此(假设您使用PHP的PDO类创建了$ pdo对象):

$stmt = $pdo->prepare("SELECT * FROM `tblsaved_mileage` WHERE `strUsername` = ?");

$stmt->execute(array($username));

$results = $stmt->fetchAll(PDO::FETCH_ASSOC); // And now you have all of your data in $results array

不需要初始化N个变量,不需要使用过时的mysql_ *扩展,不需要循环通过你得到的记录集,不需要使用addslashes等等,最终你会得到更少的代码。