duandu2980 2013-12-14 22:03
浏览 154

使用php获取MySQL错误

I'm using a for loop to go through an array and trying to make that the fields name in my database in phpmyadmin. The table gets created but my field name does not. Is there a reason for this?

At first I thought it was because of the space in each array so I replaced it with "_".

Here is my code:

<?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');

?>

The error message I'm getting are: "Array to string conversion" "Undefined offset: 1"

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VARCHAR(30) )' at line 2"

The errors are all on one line "$player[$i] VARCHAR(30) ) ") or die(mysql_error());"

  • 写回答

1条回答 默认 最新

  • duanjingsen7904 2013-12-14 22:08
    关注

    You have to change this:

    for($i = 0;$i <= $length; $i++)
    

    to

    for($i = 0; $i < $length; $i++)
    

    This is because if you have for example array with 5 items. The keys are: 0,1,2,3,4 and this for loop: for($i = 0;$i <= $length; $i++) repeats while variable $i is smaller OR equal to array count (5). So trying to get value from array with key 5 raises error.

    and for your last question change this code:

        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());  
     }
    

    to this:

    foreach($player_fromsite as $player_name) {
      mysql_query("CREATE TABLE " . $tablename . "(" . str_replace($space, $replacespace, $player_name) . " VARCHAR(30))") or die(mysql_error());   
    }
    

    and remove that $player variable and that unset($player_fromsite); code.

    评论

报告相同问题?

悬赏问题

  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统