-1

I have a wierd problem with my script that is suppose to insert the web page's source code into the database.

This script works fine when I'm fetching tiny html page on same server where this code is but when I try to fetch some other page over the internet it just won't work and it doesn't give any errors.

My own thought was that MySQL query runs before the web page is assigned to the $content variable? Is there any way to go around this?

// Set web page to fetch
$url = "http://www.webpage.com";

// Assign web page souce to variable
$content = utf8_decode(htmlspecialchars(file_get_contents($url)));

// Standard MySQL connection
$con=mysqli_connect("localhost","user","pass","db");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert web page source to database
mysqli_query($con, "INSERT INTO table_name (content) VALUES ('$content')");

//Close connection
mysqli_close($con);
  • 5
    your thought is wrong, i suspect the zero sanitation of the input is at fault –  May 21 '14 at 20:18
  • 1
    Your own thought is wrong; PHP works by line top to bottom, each line of code completing before it executes the next... learn about using prepared statements and bind variables as you're using MySQLi – Mark Baker May 21 '14 at 20:18
  • 1
    _doesn't give any error_ - how would you know? You're not checking for any. –  May 21 '14 at 20:18
  • When using `mysqli` you should be using parameterized queries and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation to accomplish this because you will create severe [SQL injection bugs](http://bobby-tables.com/). What you're doing here won't work without escaping because HTML is almost guaranteed to have both types of quotes. – tadman May 21 '14 at 20:22
  • 1
    Add error reporting to the top of your file(s) `error_reporting(E_ALL); ini_set('display_errors', 1);` during development. – Funk Forty Niner May 21 '14 at 20:35

2 Answers2

0

The REAL problem with your code is the absence of any error checking. So now you are assuming your code works and when it doesn't you wonder why. If you did, it would have saved you and others a lot of time.

if (!mysqli_query($con,"INSERT INTO table_name (content) VALUES ('$content')"))
{
    echo("An error occured: " . mysqli_error($con));
}
crafter
  • 6,246
  • 1
  • 34
  • 46
  • 1
    [Enabling exceptions](http://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) makes these sorts of things basically impossible to ignore, avoiding a lot of testing. – tadman May 21 '14 at 20:56
-2
//Insert web page source to database
$content = mysqli_real_escape_string($con,$content);
mysqli_query($con, "INSERT INTO table_name (content) VALUES ('$content')");
Flash Thunder
  • 11,672
  • 8
  • 47
  • 91