我正在使用for循环遍历一个数组,并试图将其作为phpmyadmin中数据库中的字段名称。创建了表,但我的字段名没有。这是有原因的吗?
一开始我以为这是因为每个数组中的空间,所以我用"_"代替了它。
这是我的代码:
<?php
include 'simple_html_dom.php';
include ('connection.php');
function getsquad($url, $tablename){
$html = file_get_html($url);
$player_fromsite = array();
$space = ' ';
$replacespace = '_';
$player = array();
foreach($html->find('td[align=left]') as $element) {
if ($element->children(0)) { // work only when children exists
array_push($player_fromsite ,$element->children(0)->innertext);
}
}
array_push($player, str_ireplace($space, $replacespace, $player_fromsite));
unset($player_fromsite);
$length = count($player);
for($i = 0;$i<=$length;$i++){
// Create a MySQL table in the selected database
mysql_query(" CREATE TABLE $tablename(
$player[$i] VARCHAR(30) ) ") or die(mysql_error());
}
echo "Table Created!";
}
$Squad = new squad();
$Squad->getsquad('site', 'Ars');
?>
我收到的错误消息是:"数组到字符串的转换"未定义偏移:1"
"您的SQL语法有错误;请查看与MySQL服务器版本对应的手册,在第2行的‘VARCHAR(30))’附近找到正确的语法。"
错误都在一行"$player[$i]VARCHAR(30)")或die(mysql_error());"
您必须更改以下内容:
for($i = 0;$i <= $length; $i++)
至
for($i = 0; $i < $length; $i++)
这是因为,如果您有一个5项的数组。键为:0、1、2、3、4,对于循环:for($i = 0;$i <= $length; $i++)
重复,而变量$i
小于OR等于数组计数(5)。所以,尝试用键5从数组中获取值会引发错误。
对于您的最后一个问题,请更改此代码:
array_push($player, str_ireplace($space, $replacespace, $player_fromsite)); unset($player_fromsite);
$length = count($player);
for($i = 0;$i<$length;$i++){
mysql_query(" CREATE TABLE $tablename( $player[$i] VARCHAR(30) ) ") or die(mysql_error());
}
到此:
foreach($player_fromsite as $player_name) {
mysql_query("CREATE TABLE " . $tablename . "(" . str_replace($space, $replacespace, $player_name) . " VARCHAR(30))") or die(mysql_error());
}
并且移除该CCD_ 3变量和该unset($player_fromsite);
代码。