我想将一些已解析的数据存储到mysql数据库中。我的代码如下:
<?php
include('mysql_connection.php');
include('simplehtmldom_1_5/simple_html_dom.php');
$site = "www.xyz.com/19326072316";
$html = file_get_html($site);
foreach($html->find('body') as $body)
{
foreach($body->find('a.url') as $e)
{
$title = $e->plaintext;
echo '<b>Title: </b>' . $title . '<br>';
}
foreach($body->find('a.category') as $cat)
{
$category = $cat->plaintext;
echo '<b>Category: </b>' . $category . '<br>';
}
preg_match('/(\w+)\.xyz\.com\/.+/', $site, $matches);
$city = $matches[1];
echo '<b>City: </b>' . $matches[1] . '<br>';
foreach($body->find('div.month') as $month){
$month = $month->plaintext;
echo '<b>Start and end month: </b>' . $month . '<br>';
}
foreach($body->find('div.date') as $date){
$date = $date->plaintext;
preg_match('/([0-9]{1,2})/', $date, $match_date);
$date = $match_date[0];
echo '<b>Start and end date: </b>' . $date . '<br>';
}
foreach($body->find('li.new_WatchIcon') as $time){
$time = $time->plaintext;
echo '<b>Time: </b>' . $time . '<br>';
}
foreach($body->find('li#new_locationIconIE7 div') as $address){
$address = $address->plaintext;
echo '<b>Address: </b>' . $address . '<br>';
}
foreach($body->find('span.description') as $description){
$description = $description->innertext;
echo '<b>description: </b>' . $description . '<br>';
}
$query = ("INSERT INTO articles (event_name, date_added, start_date, start_month, end_date, end_month, year, city, state, full_address, time, description, contact) VALUES('$title', now(), '$date', '$month', '$date', '$month', '2014', '$city', 'Karnatka', '$address', '$time', '$description', 'NULL')") or die(mysql_error());
$run_query = mysqli_query($query, $connection);
}
?>
当我使用mysql_query
时,没有发生任何事情,但当我使用mysqli_query
时,我遇到了以下错误:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given
我知道这个问题已被多次提出,但我尝试了解决这个问题的大部分方法,但没有任何方法可以帮助我!
答案 0 :(得分:0)
您使用的是mysqli_query()参数的错误顺序。而不是你的
$run_query = mysqli_query($query, $connection);
应该是
$run_query = mysqli_query($connection, $query);
如果您要为INSERT
查询使用带占位符的预准备语句,那将是一个很好的增强功能:
// Prepare the statement before your outer foreach loop:
$query = "INSERT INTO articles (event_name, date_added, start_date, start_month, end_date, end_month, year, city, state, full_address, time, description, contact)
VALUES (?, now(), ?, ?, ?, ?, '2014', ?, 'Karnatka', ?, ?, ?, NULL)";
// instead of mysqli_query use in the loop
if ($stmt = mysqli_prepare($connection, $query) {
// your parameters are all of string type and you have 9
mysqli_stmt_bind_param(
$stmt,
'sssssssss',
$title, $date, $month, $date, $month, $city, $address, $description);
foreach($html->find('body') as $body) {
// Please take care, that you only can assign values to those variables
// and execute the insert at the end of your loop
mysqli_stmt_execute($stmt);
}
}
说明:
我认为查询的最后一个参数是特殊值NULL
而不是字符串'NULL'
。