[英]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. 我有一个foreach循环,该循环使用从站点收集的数组中的新列名创建表。 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: H这是我的代码:
<?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 在foreach循环中,所有空格都用“ _”替换
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)
. 我不确定我是否正确理解您想要的内容:在
$player_fromsite
您有一些字符串,这些字符串应成为名称为$tablename
的新表的列,而所有列均为VARCHAR(30)
。
If so, replace your last foreach loop with the following: 如果是这样,请将以下内容替换为您的最后一个foreach循环:
$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. foreach循环基本上准备了所有列,然后将它们串联到发送到数据库的实际查询中。
So for exmaple let $player_fromsite = array('foo', 'bar')
, you would end up with the query 因此,例如让
$player_fromsite = array('foo', 'bar')
,您最终将获得查询
CREATE TABLE `Ars` (`foo` VARCHAR(30),`bar` VARCHAR(30));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.