你好,我有这个foreach循环,它给出了奇怪的结果,它只显示db记录的第一个字符
<?PHP
$result2 = MysqL_query("SELECT id,fp_thumb,title FROM media") or die(MysqL_error());
$data2 = MysqL_fetch_array($result2) or die(MysqL_error());
foreach ($data2 as $val) {
echo '<li><a href="media.PHP?id='.$val['id'].'"><img src="'.$val['fp_thumb'].'" alt="'.$val['title'].'" /></a></li>';
}
?>
这是我的数据库结构
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for media
-- ----------------------------
CREATE TABLE `media` (
`id` int(11) NOT NULL auto_increment,
`thumb` varchar(500) NOT NULL,
`url` varchar(500) NOT NULL,
`fp_thumb` varchar(500) NOT NULL,
`title` varchar(500) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records
-- ----------------------------
INSERT INTO `media` VALUES ('1', '22', 'http://goeshere.com', '/images/slideshow/ctmbs.jpg', 'Test 1');
INSERT INTO `media` VALUES ('2', '2', 'http://goeshere1.com', '/images/slideshow/hitlex.jpg', 'test 2');
INSERT INTO `media` VALUES ('3', '3 ', 'http://goeshere2.com', '/images/slideshow/tsord.jpg', 'test 3');
任何信息都是有用的
在此先感谢并欢呼^^
解决方法:
从代码中,我会说$data2表示来自DB的1行数据.
你的foreach循环是没用的:如果你想显示1行的数据,你可以直接使用$data2.
如果你想逐行进行,你不能迭代$data2,而是在MysqL_fetch_array返回数据时循环.
这样的话,我会说:
$result2 = MysqL_query("SELECT id,fp_thumb,title FROM media") or die(MysqL_error());
while ($data2 = MysqL_fetch_array($result2)) {
echo '<li><a href="media.PHP?id='.$data2['id'].'"><img src="'.$data2['fp_thumb'].'" alt="'.$data2['title'].'" /></a></li>';
}
此外,您可能想要转义您输出的数据,以确保您没有任何类型的HTML / javascript注入 – 至少在src和标题中,我会说;为此,你可以使用htmlspecialchars
那么你的回声可能看起来像这样:
echo '<li><a href="media.PHP?id='
. $data2['id']
. '"><img src="'
. htmlspecialchars($data2['fp_thumb'])
. '" alt="'
. htmlspecialchars($data2['title'])
. '" /></a></li>';
(我认为id是一个整数,自动递增或类似的东西,所以没有太大的风险)
根据你的第一次使用:
$data2是一个关联数组,如下所示:
array
'id' => int 152
'title' => string 'this is the title' (length=17)
'fp_thumb' => string 'http://...../' (length=13)
这意味着foreach将循环三次,$val将是:
int 152
string 'this is the title' (length=17)
string 'http://...../' (length=13)
(每次迭代一个值)
即,$val不是数组是标量值.
当你这样做:
$a = 152;
var_dump($a['id']);
你得到
null
做的时候
$a = 'this is the title';
var_dump($a['id']);
你得到 :
string 't' (length=1)
也就是说,只有在字符串上使用数组访问时才会获得第一个字符,并且键是一个字符串.
请注意,字符串上的数组访问使用数字键来访问数组的一个字符:
$a = 'this is the title';
var_dump($a[3]);
得到你:
string 's' (length=1)
有关更多信息,请参阅有关字符串的手册页,尤其是String access and modification by character,其中说明:
Characters within strings may be
accessed and modified by specifying
the zero-based offset of the desired
character after the string using
square array brackets, as in $str[42].
Think of a string as an array of
characters for this purpose.
而且:
Non-integer types are converted to
integer.
将’title’转换为整数得0;所以,你得到字符串的第一个字符.
希望这会有所帮助,你理解“为什么”;-)