简体   繁体   中英

Save file_get_contents in database

I want to save 10.000 pages in my site's database.

When I run the file, this error occurs for every page.

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 '_trackPageLoadTime']);(function() {var ga = document.createElement("script"); ga' at line 1

I think there are some characters that are causing the error.

savedb.php

<?php 
include "conexao.php";

for ($nr=1; $nr<=10000; $nr++){
    $url = "http://www.site.com/u$nr";
    $html = file_get_contents($url);

    set_time_limit(120);

    $tabela_bd = "paginas";

    $sql = mysql_query("INSERT INTO $tabela_bd(html) VALUES('$html')");
    if ($sql) {echo "Cadastrado com sucesso!!";
} else {
echo "Falha ao cadastrar.".mysql_error();
}

}

?>

@edit Solved my problem with characters, but now some tables are being saved without content.

Don't use the deprecated mysql_* functions. Use the mysqli_* functions instead.

Even better, use an abstraction library such as PDO, which supports the use of placeholders. This automatically applies escaping as required. See:

http://php.net/manual/en/book.pdo.php

Examples of use of placeholders:

http://www.php.net/manual/en/pdo.prepare.php

In your case, maybe this:

$stmt = $pdo->prepare("insert into $tabela_bd( html ) values ( :html )");
$stmt->bindValue('html', $html);
$stmt->execute();

Your files seem to have escape characters in them like \\ or ; . What you would need to do is to make sure that these characters don't interfere with the query.

Use this

$html = mysql_real_escape_string($html);
$sql = mysql_query("INSERT INTO $tabela_bd(html) VALUES('$html')");

You're not escaping the special characters in the html. Try mysql_escape or something of the like.

您需要转义$ html变量:

$sql = mysql_query("INSERT INTO $tabela_bd(html) VALUES('" . mysql_real_escape_string($html) . "')");

You should use mysql_real_escape_string in your situation as demonstrated below.

<?php 
include "conexao.php";

for ($nr=1; $nr<=10000; $nr++){
    $url = "http://www.power-pixel.net/u$nr";
    $html = file_get_contents($url);

    // escape the string
    $html = mysql_real_escape_string($html);

    set_time_limit(120);

    $tabela_bd = "paginas";

    $sql = mysql_query("INSERT INTO $tabela_bd(html) VALUES('$html')");
    if ($sql) {
      echo "Cadastrado com sucesso!!";

    } else {
      echo "Falha ao cadastrar.".mysql_error();
    }

}

?>

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