0

我的 mysql 表中有三个文件,它们是:id、url、status

如何检查列 url 中的所有 url 并将 1(可用)或 0(不可用)写入状态列?

要在没有 mysql 的 php 中手动检查 url,我可以使用这个:

<?php
    function Visit($url){
    $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL,$url );
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch,CURLOPT_VERBOSE,false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $page=curl_exec($ch);
    //echo curl_error($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($httpcode >= 200 && $httpcode < 300){ 
        return true;
    }
    else {
        return false;
    }
}
    if(Visit("http://www.google.com")){//maybe make it a variable from a result of a mysql select, but how to process it one by one?  
        echo "Website OK"; //maybe somesql here to wtite '1'
    }
    else{
        echo "Website DOWN";//maybe somesql here to wtite '0'
    }
?> 
4

3 回答 3

1

这在性能方面很糟糕,因为在循环中进行查询是糟糕的设计,您应该构建批量更新并最终运行查询,但我现在没有足够的时间来详细说明。这只是为了让您入门:

$sql = "SELECT id,url FROM mytable";
$res = mysql_query($sql) or die(mysql_error());
if($res)
{
  while($row = mysql_fetch_assoc($res))
  {
    $status = visit($row['url']) ? '1' : '0';
    $id = $row['id'];
    $update = "UPDATE mytable SET status = $status WHERE id = $id";
    $res = mysql_query($update) or die(mysql_error());
  }
}
于 2012-05-25T06:00:36.677 回答
0
echo mysql_num_rows($result) ? '1' : '0';
于 2012-05-25T05:47:34.313 回答
0

例如,您可以使用 sql 查询:

select id, url from urltable;
update urltable set status=1 where id=99;

那么,如何将此代码与您的访问功能一起使用:

$link = mysql_connect('localhost', 'test', 'pppppp');
$db_selected = mysql_select_db('test', $link);
$query = "select id, url from urltable";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
    $visitid =  $row['id'];
    $visiturl =  $row['url'];
    $visitstatus = Visit($visiturl)? 1: 0;
    $upquery = sprintf("update urltable set status=%d where id=%d", $visitstatus, $visitid);
    $upresult = mysql_query($upquery);
}
于 2012-05-25T06:38:02.103 回答