2014-10-09 103 views
1

我有表MYTABLE包含字段:ID,PASSWORD,COL1,COL2,COL3,DATE 我想获取并显示HTML表中的所有记录,但跳过ID和密码字段... 我使用下面的代码是不工作:PHP MySQL如何跳过显示字段

$query = "SELECT * FROM MYTABLE WHERE 1"; 
$results = mysql_query($query, $conn) or die(mysql_error()); 
echo "<tr>"; 
while ($r = mysql_fetch_assoc($results)) { 
    foreach ($r as $item) { 
     // let's not display ID and password 
     if ($r == 'ID' || $r == 'PASSWORD') continue; // this is the line that I want to figure out 
    echo "<td>$item</td>"; 
    } // end for loop 
} // end while 
unset($item); 
echo "</tr>"; 

显然有不止1点的方式来做到这一点,比如我可以用替换foreach循环的循环:

for ($i=0;$i<=6;$i++) { 
    if ($i == 0 || $i == 1) continue; 
    echo "<td>$r[$i]</td>"; 
} // end for 

这会跳过ID和PASSWOR D字段,但我不想使用它,因为我在多个表上运行代码(表名是从html select标记中提取的),并且这些表可能没有相同数量的字段/列(但它们将始终有ID和PASSWORD)。我也可以用SQL语句(我不想),但是然后我将不得不查询到一个临时工,删除ID,PASSWORD列,然后从临时表中获取。 (顺便说一下有没有令人信服的理由,为什么我其实应该与SQL Rathen市的比PHP做呢?)

+0

为什么你就不能使用 “从MYTABLE选择COL1,COL2,COL3,DATE”? – Akhil 2014-10-09 12:24:23

+0

因为他很伤心:“这会跳过ID和PASSWORD字段,但我不想使用它,因为我在多个表上运行代码(表名是从html选择标记中提取的)” – vaso123 2014-10-09 12:27:27

回答

0

试试这个:

$query = "SELECT * FROM MYTABLE WHERE 1"; 
$results = mysql_query($query, $conn) or die(mysql_error()); 
echo "<tr>"; 
while ($r = mysql_fetch_assoc($results)) { 
    foreach ($r as $key => $item) { 
     // let's not display ID and password 
     if (!in_array($key, array('PASSWORD', 'ID'))) { 
      echo "<td>$item</td>"; 
     } 
    } // end for loop 
} // end while 
echo "</tr>"; 
+0

我差点忘了in_array。非常感谢你,我要去解决这个问题。 – firewire 2014-10-09 12:45:11

+0

关键不是in_array,我只是用它来不做OR运算符。这一点是$ r作为$ key => $ item。 – vaso123 2014-10-09 14:50:23

+0

哦,是的,我同意队友,它是$ r = $ k => $ item。我只是注意到in_array的用法。再次,非常感谢您的帮助。 – firewire 2014-10-09 22:15:22

1

我会建议你做这种方式:

$query = "SELECT COL1, COL2, COL3, DATE FROM MYTABLE WHERE 1"; 
+0

感谢回答队友,但就像我说过我不应该用SQL来做:1.真正的表格有超过24个字段/栏目2.有很多表格,他们没有等量的字段 – firewire 2014-10-09 12:34:52

+0

对不起,我必须已经读得很快,以为你只想重新使用循环。幸运的是,你有更多的答案:-) – 2014-10-09 12:43:32

1
foreach ($r as $k => $item) { 
    // let's not display ID and password 
    if ($k == 'ID' || $k == 'PASSWORD') continue; 
    echo "<td>$item</td>"; 
} 

这符合正是你的要求。
我希望这个结果现在对你有用,之后,你从它演变而来。

+0

这工作。万分感谢! – firewire 2014-10-09 12:43:55

0

让它容易..

<?php 
$query = "SELECT COL1, COL2, COL3, DATE FROM MYTABLE WHERE ..whatever.."; 
$result = mysql_query($query); 

if ($result) { 
    while ($row = mysql_fetch_array($result)) { 
     echo "<tr>"; 
     echo "<td>".$row["COL1"]."</td>"; 
     echo "<td>".$row["COL2"]."</td>"; 
     echo "<td>".$row["COL3"]."</td>"; 
     echo "<td>".$row["DATA"]."</td>"; 
     echo "<tr>"; 
    } 
} 

?> 
+0

不能这样做。有多个表,它们没有相同数量的字段,也没有相同的名称(ID和PASSWORD除外)。感谢你的回答。 – firewire 2014-10-09 12:48:39