[英]Parsing HTML tags to PDO MySQL
我的代碼是使用正則表達式解析HTML標簽並將所有鏈接存儲為數據庫中的數組
我的代碼有問題,我不知道如何解決它以保存MySQL內部的鏈接
我看到此錯誤消息錯誤:SQLSTATE [HY093]:無效的參數編號:列/參數基於1
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;
當綁定的參數,你需要指定:
在參數名:
$stmt->bindParam(':' . $search_field, $search_val);
您會收到一條錯誤消息,因為它丟失了,並且代碼回落到期望整數值指示參數位置的位置(就像您正在使用?樣式的參數一樣)。
請注意文檔中對PDOStatement :: bindParam()的第一個參數的描述。
參數
參數標識符。 對於使用命名占位符的預備語句,這將是:name形式的參數名稱。 對於使用問號占位符的准備好的語句,這將是參數的1索引位置。
將數據傳遞給預准備語句的方式不正確,您使用了數組的索引-這是一個基於0的數字索引數組。 這就是為什么您得到錯誤。 盡管不確定為什么需要此數組...
$rows = array($domain, $url);
相反,我建議使用...
$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();
}
這還應該為每個URL插入一條記錄,而不是最后一個URL,因為execute()
在循環內。
更新:
您還需要修改構建URL列表的代碼,該代碼以前一直覆蓋着最后一個URL,這將創建所有URL的列表。
$url = array();
foreach($matches as $match) {
$url[]=$match[2];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.