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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里