简体   繁体   中英

array set as a column name from an array using php mysql

I have an foreach loop that is creating a table with new column names from an array collected from a site. At the moment only the first element of the array is being set as a column name, can someone help?

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

//$player[] = str_replace($space, $replacespace, $player_fromsite);
//unset($player_fromsite);

$length = count($player);

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

echo "Table Created!";

}

$Squad = new squad();
$Squad->getsquad('site', 'Ars');

?>

any spaces are replace with a "_", in the foreach loop

I am not quite sure if I correctly understand what you want: In $player_fromsite you have some strings, which should become columns of the new table with the name from $tablename , whereas all columns are VARCHAR(30) .

If so, replace your last foreach loop with the following:

$columns = array();
foreach ($player_fromsite as $player_name) {
    $columns[] = '`' . str_replace($space, $resplacespace, $player_name) . '` VARCHAR(30)';
}
$query = 'CREATE TABLE `' . $tablename . '` (' . implode(',', $columns) . ')';
mysql_query($query) or die(mysql_error());

The foreach loop basically prepares all the columns, which afterwards get concatenated to the actual query which is send to the database.

So for exmaple let $player_fromsite = array('foo', 'bar') , you would end up with the query

CREATE TABLE `Ars` (`foo` VARCHAR(30),`bar` VARCHAR(30));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM