如何将PHP数组插入MYSQL数据库?
嗨Garbel,
我发现你的文章将HTML表数据转换成PHP数组的简单方法,它碰巧用项目创建了一个精美的数组我正在努力。我想把这个数组输入我的mysql数据库。遗憾的是没有太大成功我需要一个计数器,因为html文件可能有更多或更少的列和行,并且很难弄清楚如何这样做。您可以给我的任何输入将不胜感激。到目前为止,我会附上我在代码中写的内容,这样你就可以知道我在哪里了。
谢谢!
我尝试过:
Hi Garbel,
I found your article "Simple Way to Convert HTML Table Data into PHP Array" and it happened to create an array beautifully with a project I was working on. I am trying to enter this array into my mysql db. Unfortunately without much success. I need a counter as the html file may have more or less columns and rows and have had a hard time figuring out how to do so. Any input you could give me would be greatly appreciated. I will attach what I have written in code so far so you have an idea of where I am at.
Thanks!
What I have tried:
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$database = "ticker";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$table = file_get_contents("watchlist.html");
$dom = new DOMDocument;
@$dom->loadHTML($table);
$tds = $dom->getElementsByTagName("td");
$tags = $dom->getElementsByTagName("th");
$symbol = $tags->item(0)->nodeValue;
$vwap = $tags->item(1)->nodeValue;
$last = $tags->item(2)->nodeValue;
$trend = $tags->item(3)->nodeValue;
$bid = $tags->item(4)->nodeValue;
$ask = $tags->item(5)->nodeValue;
$volume = $tags->item(6)->nodeValue;
$markchg = $tags->item(7)->nodeValue;
$markpcnt = $tags->item(8)->nodeValue;
$shares = $tags->item(9)->nodeValue;
$marketcap = $tags->item(10)->nodeValue;
$ttmsqz = $tags->item(11)->nodeValue;
foreach($tags as $NodeHeader)
{
$aDataTableHeaderHTML[] = trim($NodeHeader->textContent);
}
//print_r($aDataTableHeaderHTML); die();
$i = 0;
$j = 0;
foreach($tds as $sNodeDetail)
{
$aDataTableDetailHTML[$j][] = trim($sNodeDetail->textContent);
$i = $i + 1;
$j = $i % count($aDataTableHeaderHTML) == 0 ? $j + 1 : $j;
}
print_r($aDataTableDetailHTML); die();
//this is where your sql goes
$query = "INSERT INTO riser (symbol, vwap, last, bid, ask, volume, markchg, markpct, shares, marketcap, ttmsqz) VALUES ('$aDataTableDetailHTML[0][0]', '$aDataTableDetailHTML[0][1]', '$aDataTableDetailHTML[0][2]', '$aDataTableDetailHTML[0][3]', '$aDataTableDetailHTML[0][4]', '$aDataTableDetailHTML[0][5]', '$aDataTableDetailHTML[0][6]', '$aDataTableDetailHTML[0][7]', '$aDataTableDetailHTML[0][8]', '$aDataTableDetailHTML[0][9]', '$aDataTableDetailHTML[0][10]', '$aDataTableDetailHTML[0][11]')";
mysql_query($query);
$conn->close();
?>
servername =localhost;
servername = "localhost";
username = user;
username = "user";
password =pass;
password = "pass";