【发布时间】:2018-04-21 02:57:43
【问题描述】:
我有一个 MySQL 表字段,其中包含一个指向图像的 URL。我正在使用 php 并希望图像与其他字段一起显示在表格中。
我想我需要使用 PHP Switch 语句并引用 Row('Name') 或 Field Ref Number 来创建代码。我在 classic-asp 中可以正常工作,但需要在 php 中编写代码。
$result = mysql_query("SELECT sometext,urlvalue,somemoretext FROM Table");
if (!$result) {
die("Query to show fields from table failed");
// Table fields
// sometext
// urlvalue an http image address such as http://www.example.com/image.jpg"
// somemoretext
$fields_num = mysql_num_fields($result);
echo "<table border='1'>
<tr bgcolor='yellow' align='left'>";
for($i=0; $i<$fields_num; $i++) {
$field = mysql_fetch_field($result);
echo "<th>{$field->name}</th>";
}
echo "\n";
// printing table rows
while($row = mysql_fetch_row($result)) {
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
switch $fields_num {
case "2":
// result cell looks like this ---->
// <td><a target='_blank' href='http://www.example.com/image.jpg'><img src='http://http://www.example.com/image.jpg'></a></td>
echo "<td><a target='_blank' href='" . $cell ."'><img src='" . $cell ."'></a></td>";
break;
default:
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
【问题讨论】:
-
我可以提供三个建议:1.不要回显,而是构建一个字符串,并在最后回显它 2.如果你能清理源代码,提供准确的帮助会更容易 3 . 你能描述一下你遇到的实际问题 - 即你认为你的输出应该是什么,而不是你实际得到的。
-
请停止使用
mysql_函数。 -
switch的参数必须在括号中:switch ($fields_num) { ... } -
请详细说明您的表结构和列名,以便我们为您提供明确的答案。
-
@John 您是否事先知道您在查询中选择了哪些行?还是您在 SELECT 子句中使用
*?你的项目有多变数?
标签: php html mysql switch-statement