如何检查列名是否"name"?



我有一个表格:-

|----------|-----------------------------------------|------------------|
|    id    |        name                             |    desc          |
|----------------------------------------- ----------|------------------|
|    123   |   Empire : Kill (Kill everybody now)    |    desc 1        |
|----------------------------------------------------|------------------|
|    243   |   Witch : Show (Bloodthirst part 2)     |    desc 2        |
|----------------------------------------------------|------------------|

我正在编写以下代码以从表中提取数据:-

$columns_total  = mysql_num_fields($result); 
while ($row = mysql_fetch_array($result)) //retrieving each row 
    {
        for ($i = 0; $i < $columns_total; $i++) 
        {
            /*appending each column data into the row of the data 
                encapsulated within double quotes and separated by a comma */
            $output .='"'.$row["$i"].'",';
        }
    }

我必须检查$row[$i]name列的值还是desc列的值?

如果是name列,则括号下的文本将被删除,否则不会

我怎样才能做到这一点?

我建议使用关联数组..也是一个foreach循环,如下所示:

while ($row = mysql_fetch_assoc($result)) //retrieving each row's ASSOCIATIVE ARRAY 
    {
        foreach ($row as $key => $value)  // $key will hold the name of the field
        {
            // now you can go like this:
            if($key != 'name')
                $output .= '"'.$value.'",';
            else
                // whatever you want 
        }
    }

作为旁注,mysql_函数已被弃用。您应该改用mysqli_PDO

使用 mysql_fetch_array($result, MYSQL_ASSOC))。这样,您的结果就会返回:

array (
    'id'=>123,
    'name'=>"Whatever the name is",
    'desc'=>"desc 1"
);
foreach ($row as $name=>$value)
   ...

尝试使用 foreach

foreach($row as $key => $value)
{
     if($key == 'name')
     {
         ...
     }
}

$key将是数组的索引键,$value是该数组的值,因此

'key' => 'value'

最新更新