简体   繁体   中英

insert array into database syntax error

I'm parsing article links from a friend's basketball website using DOM Parser . I want to store these values in my database but I'm getting a syntax error Here's the code:

<?php
include_once ('connect_to_mysql.php');
    include_once ('simple_html_dom.php');
    $html = file_get_html('http://basket-planet.com/ru/');
    $main = $html->find('div[class=mainBlock]', 0);
    $items = array();
        foreach ($main->find('a') as $m){
            $items[] = "$m->plaintext, $m->href";
        }
    //print_r($items);
    $reverse = array_reverse($items);
    print_r($reverse);

    $sql = mysql_query ("INSERT INTO basket_news (article, link) VALUES ".(implode(',', $reverse))."") or die (mysql_error());
?>

This is the output from the reverse array (sorry, it's in a nother language):

Array (
  [0] => 07:43 Видео. Дэвид Стерн и арбитры вручают "Лейкерс" победу над "Миннесотой" (1) , /ru/news/9234
  [1] => 07:51 "Чикаго" прервал победную серию "Майами" на отметке 27 (0) , /ru/news/9235
  [2] => 15:02 Кабмин выделил 200 млн грн на подготовку к Евробаскету (0) , /ru/news/9243
  [3] => 20:42 Евролига: ЦСКА ломает мадридский «Реал» (0) , /ru/news/9246
  [4] => 21:45 «Уникаха» побеждает в Стамбуле и молится на «Бамберг» (0) , /ru/news/9248 )

And here's the error:

You have an error in your SQL syntax; check the manual that corresponds to your 
MySQL server version for the right syntax to use near 
'07:43 Видео. Дэвид Стерн и ' at line 1

What am I doing wrong here? Please advise...

Change to:

foreach ($main->find('a') as $m)
{
  $items[] = "'$m->plaintext', '$m->href'";
}

And

"INSERT INTO basket_news (article, link) VALUES (" . implode('), (', $reverse) . ")"

Also, ensure you escape your input (or ideally use prepared statements ).

The string is not delimited with quotes and not escaped in your code. The Values string should contained by ( and ) So the right way if you use mysql:

  $items[] = "('".mysql_real_escape_string($m->plaintext)."','".
                  mysql_real_escape_string($m->href)."')";

And as the other commenters said, you should try out mysqli , or PDO in php. The query building is easier and safer than mysql_* functions. (And mysql_* functions will be deprecated in the next version of PHP)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM