user2999924 user2999924 - 4 months ago 60
PHP Question

How to play a video in a database BLOB using php?

I have managed to upload a video (<2MB) to my table as a LONGBLOB type. The table name is test2 in database 'test'. But i cant play an mp4 video. This is my code.

<?php
echo 'h';
$arr=array();
$con=mysql_connect('localhost','root','46');
mysql_select_db('test',$con);
$query="select video from test2";
$result=mysql_query($query,$con);
$arr=mysql_fetch_array($result);
header('content-type: video/mp4');
echo $arr[0];
?>


Thanks.

Answer

In case you really want to store videos as databases blobs (I don't recommend so), this should work:

<?php
mysql_connect('localhost', 'root', '46') or die('Could not connect to MySQL server');
mysql_select_db('test') or die('Could not select database');

if (($result = mysql_query('SELECT video FROM test2')) !== false) {
    header('Content-Type: video/mp4'); 
    print mysql_result($result, 0);
} else {
    // actions to take if it fails
}

Even better you might want to use PDO to query the database:

<?php
$db = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', '46');

if (($result = $db->query('SELECT video FROM test2')) !== false) {
    header('Content-Type: video/mp4');
    print $result->fetch(PDO::FETCH_COLUMN);
} else {
    // actions to take if it fails
}
Comments