Domanda

I have i little problem with inserting .jpg image to database by PHP script. DB connection is working fine for sure, query is working in phpmyadmin, so I think the problem is in the PHP code. There is my db table:

CREATE TABLE images(
imageid INT( 11 ) PRIMARY KEY AUTO_INCREMENT ,
noteid INT( 11 ) NOT NULL ,
image LONGBLOB NOT NULL ,
FOREIGN KEY ( noteid ) REFERENCES notes( noteid ) 
ON UPDATE CASCADE ON DELETE RESTRICT
);

And there is the script for test:

// connecting to db
$db = new DB_CONNECT();

$path = "uploads/1_image_003.jpg";
$noteid = 3;
if(file_exists($path)) {

    $handle = fopen($path, "rb");

    $image = fread($handle, filesize($path));

    fclose($handle);

    $img = base64_encode($image);

    $sql ="INSERT INTO images(noteid, image) VALUES('$noteid', '$img')";

    mysql_query($sql) or die('Bad Query');
    if (!mysql_query($sql)) { // Error handling
        echo "Something went wrong! :("; 
    }
} else {
    echo "File not found\n";
}

That script returning "Bad Query". Do you have any suggestions what is wrong or could you direct me to another way to store .jpg image to mysql?

È stato utile?

Soluzione

Try with file_get_contents()

$img =mysql_real_escape_string(file_get_contents($path));
$sql ="INSERT INTO images(noteid, image) VALUES('$noteid', '$img')";
mysql_query($sql) or die('Bad Query : '.mysql_error());

Note:

  1. You should avoid using mysql_* functions, you should use mysqli_* or PDO instead.

  2. Don't store files to database (unless its extremely required). You could just store file path to database. for more..

Altri suggerimenti

I think you need to debug this a little bit further to determine the problem.

Add the following before your code:

error_reporting(-1);
ini_set('display_errors', 'On');

Also, as suggested below try replacing:

mysql_query($sql) or die('Bad Query');

With

mysql_query($sql) or die('Bad Query'. mysql_error());

Replace

mysql_query($sql) or die('Bad Query');
if (!mysql_query($sql)) { // Error handling
    echo "Something went wrong! :("; 
}

with

if ( !mysql_query($sql) ) { // Error handling
    die( 'Bad Query' . mysql_error() );
}

You should consider using MySQLi or PDO_MySQL extensions instead of mysql_query() since it is deprecated.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top