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 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径