试图从网站内容新闻中插入数据。
下面是页面源的内容,我正在尝试从该页提取数据后插入。
我想提取的网站的页面源的例子
<html>
...
<div class=story-box>
<img src="http://www.example.com/assets/images/CM.gif">
<h2>Heading</h2>
<p>afsdfdfha adhfaksdhf adfhakhf adfhaskfdha fsahfkasdhfaasfdjhasdf ahdfkahsd</p>
<p>afsdfdfha adhfaksdhf adfhakhf adfhaskfdha fsahfkasdhfaasfdjhasdf ahdfkahsd</p>
<p>afsdfdfha adhfaksdhf adfhakhf adfhaskfdha fsahfkasdhfaasfdjhasdf ahdfkahsd</p>
<p>yuoyuouoyuoyuyu oyuiouioyuioyuyiouyoiy youyoiyuioyuioyuyoiuyiuyiyuioyu yuyiu</p>
</div>
...
</html>
我想提取并插入到数据库的内容的标题(内标签),图像(内标签),在p标签的所有内容。
<?php
include('simple_html_dom.php');
$url = 'http://www.example.com';
$html1=file_get_html($url);
$heading=$html1->find("div.story-box h2",0);
$heading1=strip_tags($heading);
echo $heading;
$image=$html1->find("div.story-box img",0);
$image1=strip_tags($image);
echo $image;
$content=array();
foreach($html1->find('div.story-box p') as $e)
{
$content=$e;
$content1=strip_tags($content);
echo "$e <br>";
}
?>
这是在上面的php代码后插入数据库的过程
if(isset($_GET['submit']))
{
$connect = mysql_connect("localhost","root","");
if(! $connect )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test1");
$sql = 'INSERT INTO test1 '.
'(heading,image, article) '.
'VALUES ( "$heading1", "$image1", "$content1")';
$retval = mysql_query( $sql, $connect );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully'n";
mysql_close($connect);
}
?>
这是我创建mysql表的SQL语句
CREATE TABLE IF NOT EXISTS `test1` (
`heading` varchar(400) NOT NULL,
`image` blob NOT NULL,
`article` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
但是在数据库中,我只得到$heading1 $image1 $content1而不是实际数据
VALUES字段需要引号,因为它们是字符串。由于您正在进入数据库的数据是未知的,我还在数据周围添加了mysql_real_escape_string函数,以保护您并对其进行消毒。
$sql = 'INSERT INTO test1 '.
'(heading,image, article) '.
'VALUES ( "'. mysql_real_escape_string($heading1) . '", "'. mysql_real_escape_string($image1) . '", "'. mysql_real_escape_string($content1). '")';
尝试从$sql中的变量名中删除引号,即,代替"$heading"尝试$heading,因为这是变量名
试试这样写代码:
$sql = 'INSERT INTO test1 '.
'(heading,image, article) '.
'VALUES ( '. $heading1. ', '. $image1. ', '. $content1. ')';
就像你之前做的"。"字符串连接器。