我使用了一个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())上;”
发布于 2013-12-15 06:08:56
你必须改变这一点:
for($i = 0;$i <= $length; $i++)至
for($i = 0; $i < $length; $i++)这是因为,例如,如果您有包含5项的数组。关键字是:0,1,2,3,4和this for循环:for($i = 0;$i <= $length; $i++)重复,而变量$i更小,或等于数组计数(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());
}并删除该$player变量和该unset($player_fromsite);代码。
https://stackoverflow.com/questions/20588774
复制相似问题