dopuzf0898 2018-11-08 12:34
浏览 30
已采纳

将HTML标记解析为PDO MySQL

My code is Parsing HTML tags using regex and store all the links as an array inside the data base

I have a problem in my code i don't know how to fix it to save the links inside MySQL

i see this error message Error: SQLSTATE[HY093]: Invalid parameter number: Columns/Parameters are 1-based

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $domain = "https://google.com";
    $input = @file_get_contents($domain) or die("Could not access file: $domain");
    $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
    if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) {
        foreach($matches as $match) {
            $url=$match[2];
            // $match[2] = link address
            // $match[3] = link text
        }
    }   
    $rows = array($domain, $url);
    $stmt = $conn->prepare("INSERT INTO linkss(id, domain, url) 
                            VALUES (NULL, :domain, :url)");
    foreach($rows as $key => $value){
        $stmt->bindParam($key, $value);
    }
    $stmt -> execute();  
    echo "New records created successfully"; 
}
catch(PDOException $e){
    echo "Error: " . $e->getMessage();
}
$conn = null;
  • 写回答

2条回答 默认 最新

  • douzhouhan4618 2018-11-08 12:39
    关注

    The way you are passing the data to the prepared statement is incorrect, you using the index to the array - which is a 0 based numerically indexed array. This is why you get the error. Although not sure why you need this array...

    $rows = array($domain, $url);
    

    Instead I would suggest using...

    $stmt = $conn->prepare("INSERT INTO linkss(id, domain, url) 
                              VALUES (NULL, :domain, :url)");
    foreach($url as $value){
         $stmt->bindParam(':domain', $domain);
         $stmt->bindParam(':url', $value);
         $stmt -> execute();  
    }
    

    This should also insert a record for each URL rather than the last one as the execute() is inside the loop.

    Update:

    You also need to amend the code which builds the list of URL's, this was previously overwriting the last URL all the time, this will create a list of all of the URLs...

    $url = array();
    foreach($matches as $match) {
        $url[]=$match[2];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line