从其他页面中提取后无法将数据插入数据库mysql

时间:2014-07-08 08:56:03

标签: php html sql dom

尝试从网站上的内容新闻中插入数据 下面是页面源代码的内容,我试图从这个页面中提取后插入数据。

我要提取的网站的网页来源示例

<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;

但是在数据库中我只得到$ he​​ading1 $ image1 $ content1而不是实际数据

3 个答案:

答案 0 :(得分:1)

你的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). '")';

答案 1 :(得分:0)

尝试从$ sql中的变量名中删除引号,即代替&#34; $ heading&#34;尝试$ heading,因为那是变量名。

答案 2 :(得分:0)

使用类似的东西试试你的代码:

    $sql = 'INSERT INTO test1 '.
   '(heading,image, article) '.
   'VALUES ( '. $heading1. ', '. $image1. ', '. $content1. ')';

就像你之前用“。”做的那样。字符串连接器。