将单个PHP mySQL更新转换为大规模MySQL更新

时间:2017-01-12 14:27:54

标签: mysql curl foreach

好的,谢谢你的反馈,直到现在,我有以下几点:

<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "madtags";


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 


$sql = mysqli_query($conn, "SELECT id from users");
$userinfo = array();

while ($row_user = $sql->fetch_assoc())
    $userinfo[] = $row_user;

foreach ($userinfo as $user) {

$url = "http://www.pdga.com/player/".$user['id'];
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);


$dom = new DOMDocument();
@$dom->loadHTML($html);

$xpath = new DomXPath($dom);
$class = 'current-rating';
$divs = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");

foreach($divs as $div) {
    preg_match('/Current Rating:\s+(\d+)/', $div->nodeValue, $results);
}

$sql = "UPDATE users SET rating=$results[1] WHERE id=id";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully <br>";
} else {
    echo "Error updating record <br> " . $conn->error;
}

$conn->close();


}

?>

通过更改&#34;其中&#34;第45行&#34; $ sql =&#34; UPDATE用户SET rating = $ results [1] WHERE id = id&#34 ;;&#34;,我可以让它正常运行(这是一个测试6行数组)

Record updated successfully 
Error updating record 
Error updating record 
Error updating record 
Error updating record 
Error updating record 

但我想我错误地定义了一些错误,因为在第一次运行后它无法更新记录。

想法?

原帖

我正在创建一个竞赛网站,与全球网站使用的评级系统平行。所以基本上我已经创建了下面的代码来征集网站的评级。

自创建以来,会员基数大幅增加。因此,为每个成员单独创建此代码不再有用。所以我需要开发它来基本上运行我的MySQL表中的每一行(这个代码每两周运行一次)。

<?php 
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "madtags";
$url = "http://www.pdga.com/player/***ID***";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);

$dom = new DOMDocument();
@$dom->loadHTML($html);

$xpath = new DomXPath($dom);
$class = 'current-rating';
$divs = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");

foreach($divs as $div) {
    preg_match('/Current Rating:\s+(\d+)/', $div->nodeValue, $results);
}

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "UPDATE users SET rating=$results[1] WHERE id=***ID***";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

因此,每个单独行的基本变量是标记为 ID ($ url和$ sql update)的部分。

此外,该表当前具有4列&gt;&gt; id,名称,标签,评级

提前感谢一大堆。

0 个答案:

没有答案