I am getting data and while in a loop, trying to insert it into a mysql table. The first insert (of many at a time) works, but after the first entry, I get the error for every attempt thereafter in the script.
Success:
A new entry has been added with the id
of 0.
Error:
mysqli::query(): Couldn't fetch mysqli (Which gets repeated several times, from several other query attempts.)
Code:
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($resultspage);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$data = array();
$rows = $xpath->query('//p[@class="row"]'); // get all rows
foreach($rows as $entries) { // loop each row
$entry = array();
$entry['title'] = $xpath->query('./span[@class="txt"]/span[@class="pl"]/a', $entries)->item(0)->nodeValue;
$entry['link'] = 'http://' . $base_url . $xpath->query('./a[@class="i"]', $entries)->item(0)->getAttribute('href');
$entry['price'] = $xpath->query('./span[@class="txt"]/span[@class="l2"]/span[1]', $entries)->item(0)->nodeValue;
$location = $xpath->query('./span[@class="txt"]/span[@class="l2"]/span[2]', $entries)->item(0)->nodeValue;
$loc = str_replace(array('(', ')'), '', $location);
$entry['location'] = $loc;
$entry['seller'] = $xpath->query('./span[@class="txt"]/span[@class="l2"]/a', $entries)->item(0)->nodeValue;
//Get Address
$url2 = $entry['link'];
$page = file_get_contents($url2);
$dom2 = new DOMDocument();
libxml_use_internal_errors(true);
$dom2->loadHTML($page);
libxml_clear_errors();
$xpath2 = new DOMXpath($dom2);
$mapsection = $xpath2->query('//div[@class="mapAndAttrs"]');
$entry['address'] = $xpath2->query('//div[@class="mapAndAttrs"]/div[@class="mapbox"]/div[@class="mapaddress"]')->item(0)->nodeValue;
//End of Get Address
$text_node = $xpath->query('./span[@class="txt"]/span[@class="l2"]/span[1]/following-sibling::text()[1]', $entries)->item(0)->nodeValue;
// remove "/"" and "-"" | explode by space | filter space (now, its left by 2 values: bedroom and size)
$text_node = array_filter(explode(' ', str_replace(array('/', '-'), '', $text_node)));
$entry['bedrooms'] = array_shift($text_node); // bedroom
$entry['dimensions'] = array_shift($text_node); // dimensions
$data[] = $entry; // after gathering necessary items, assign inside
//put data into db
$q = "INSERT INTO `list` (`title`,`price`, `rooms`, `dimensions`, `location`, `address`, `seller`, `href`) VALUES ('".$entry['title']."','".$entry['price']."', '".$entry['bedrooms']."','".$entry['dimensions']."','".$entry['location']."','".$entry['address']."','".$entry['seller']."','".$entry['link']."')";
if ( $mysqli->query($q) ) {
echo "A new entry has been added with the `id` of {$mysqli->insert_id}.";
} else {
echo "There was a problem:<br />$q<br />{$mysqli->error}";
}
//Close it off
$mysqli->close();
}
echo '<pre>';
print_r($data);
I would like somebody to assist me with understanding why all of these queries (after the first one) are unsuccessful. I am trying to get all queries to insert. Thanks for your time!