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.
You shouldn'd be fetching the whole video into memory from the database at once, because it will stay in memory the whole time while the client is playing/downloading it. With more concurrent users, every PHP backend will keep its own copy of the video in memory. This will make your server run out of memory pretty quickly.
You could use substr() in the SQL query to fetch it in chunks, but that would put more load on the database. Better to split it in chunks before inserting it to the database.
Or, you know, just serve it directly from the file system with Apache (or any web server), like $deity intended.
I stumbled on this question in my search for similar.
If you want to not use header and play in a div or other html container from a sql blob do this:
function displayvideo(){
global $db_user, $db_password, $media_db_name, $db_host;
$video = "some_video.mp4";
$dbconnect = 'mysql:dbname='.$media_db_name.';host='.$db_host.'';
try {
$db = new PDO($dbconnect, $db_user, $db_password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
if (($result = $db->query('SELECT video FROM videos WHERE `name` = "'.$video.'"')) !== false) {
echo '<div content="Content-Type: video/mp4">
<video width="700" height="450" controls="controls" poster="image" preload="metadata">
<source src="data:video/mp4;base64,'.base64_encode($result->fetch(PDO::FETCH_COLUMN)).'"/>;
</video>
</div>';
} else {
// actions to take if it fails
}
}
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
}
Related
I am attempting to build a database driven site whereby images are loaded via a php script like so;
<img src="get_image.php?holderID=2">
I can get images to load from a folder outside the root directory when the database is accessible but I also want to be able to load a default image if there is a failure with making the database connection. The DB connection is initiated form a separate php connection file mysqli_template_connect.php;
DEFINE('DB_USER', 'someusername');
DEFINE('DB_PASSWORD', 'amnesia');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_NAME', 'template');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
and then config.inc.php sets some constants, one of which is for all DB connections;
define('MYSQL', '../../../dbconnect/mysqli_template_connect.php');
The get_image.php file then has a database connection conditional;
require('includes/config.inc.php');
REQUIRE(MYSQL);
$holderID = $_GET['holderID'];
if(!$dbc){
$image_name = 'img/unavailable.png';
$info = getimagesize($image_name);
header("Content-Type: {$info['mime']}\n");
readfile($image_name);
}
else {
$query = "SELECT imageID FROM image_holder WHERE image_holderID = $holderID ";
$result = #mysqli_query($dbc, $query);
$number_rows = mysqli_num_rows($result);
if ($number_rows == 1) {
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$imageID = $row[0];
}
else {
$imageID = FALSE;
}
if ($imageID) {
$query = "SELECT file_name FROM image WHERE imageID = $imageID";
$result = mysqli_query($dbc, $query);
$number_rows = mysqli_num_rows($result);
if ($number_rows == 1) {
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$image_name = '../../../uploads/' . $row[0];
}
else {
$image_name = 'img/unavailable.png';
}
}
else {
$image_name = 'img/unavailable.png';
}
$info = getimagesize($image_name);
header("Content-Type: {$info['mime']}\n");
readfile($image_name);
mysqli_close($dbc);
}
If I disable the MYSQL database in XAMP, the default image unavailable.png will not load even though the header and readfile section of code is virtually the same in the section of code that does work. I'm quite a newbie to all this so any ideas on loading the default image would be appreciated.
Depending on the database object you are using (MySQLi/PDO/etc), you can check if they connected. PDO returns a boolean that you can run against.
Since PDO is the most popular, I will provide an example of that. If you use something else, feel free to comment and I can clarify.
$connected = true;
if (!extension_loaded('PDO'))
{
$connected = false;
}
if (!extension_loaded('pdo_mysql'))
{
$connected = false;
}
try
{
$pdo = new PDO("mysql:host={$host};dbname={$db}", $user, $pass);
}
catch(PDOException $e)
{
$connected = false;
}
if(!$connected){ /* Load default image */ }
Note: just make sure you use the correct image headers.
Instead of
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
Use
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
hopefully it should work..
I have similar code that do the almost the same thing.
I suspect it was the header, since I have a bit more info added to the header. No harm for you to try out.
header('Content-Description: File Transfer');
header('Content-Type: '. $file_content_type);
header('Content-Length: ' . filesize($file_full_path));
header('Content-Disposition: inline; filename=' . $file_name);
readfile($file_full_path);
I want to load image, but the solution that I can get so far is loading a separate script with db - reconnection.
I have a init.php file which basically start up the application with db connection.
looks something like this.
if(!isset($_SESSION)){
session_start();
}
//error_reporting(0); //dont show path name errors when error occurs
// include required files
require 'databases/connect.php';
I have this line of code which tells the blob script to retrieve image Data
<img src="../core/functions/images.php?image_id=<?php echo $responses[$i]['product_id']; ?>" height="150" width="180" alt=""/>
And this is the problem script that re-connect db again and then retrieve the image data. If I do not reconnect the db, the mysql script will fail. Any help on this, so I don't need to reconnect db?
$connect_error = "Sry, we are working on an error, try later";
mysql_connect('localhost','root','') or die($connect_error);
mysql_select_db('SJ3') or die($connect_error);
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
?>
Using Johnboy's tutorial on importing .csv files to MySQL, I tried to make a script that would take exchange rate data from Yahoo finance, and write it to the MySQL database.
<?php
//connect to the database
$host = "****"
$user = "****"
$password = "****"
$database = "****"
$connect = mysql_connect($host,$user,$password);
mysql_select_db($database,$connect);
//select the table
if ($_FILES[csv][size] > 0) {
//get the csv file
$symbol = "ZARINR"
$tag = "l1"
$file = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=$tag&s='$symbol'=x";
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO ZAR_to_INR(exchange_rate) VALUES
(
'".addslashes($data[0])."',
)
");
echo "done";
}
} while ($data = fgetcsv($handle,1000,",","'"));
//redirect
header('Location: import.php?success=1'); die;
}
else{
echo "nope";
}
?>
I added the echos in the hope that they'd tell me whether or not the script worked. It doesn't work at all. There are no error messages or anything. When I run the script by opening it in my webhost, it simply does not run.
I'd appreciate any advice on how to make this script work (or even an alternate way of solving the problem).
try using mysql debugs :
mysql_select_db($database) or die('Cant connect to database');
$result = mysql_query($query) or die('query fail : ' . mysql_error());
$connect = mysql_connect($host,$user,$password)
or die('Cant connect to server: ' . mysql_error());
to find this outputs you need to check your php error_log : where-does-php-store-the-error-log
guys. I would like to make this script, or other with the same effect:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
To create databases with different names, for example:
First time will create database named "news1", the next time, the script will just do sth. like that: news1+1 = news2, and will create database called news2, and so on...
I hope you got my point and I'll really appreciate it if you help me to make this...
Regards, Denis Saidov.
To do this I'm guessing that you don't just want to loop 100 times?
You will need to save a variable to a text file then call it again.
Writing $text to a file:
$var_str = var_export($text, true);
$var = "<?php\n\n\$$text = $var_str;\n\n?>";
file_put_contents('filename.php', $var);
Retrieving it again:
include 'filename.php';
echo $text;
All together:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_number = get_var();
$my_db = 'news' . $db_number;
if (mysql_query("CREATE DATABASE ".$my_db,$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
$new_db_number = $db_number + 1;
save_var($new_db_number);
mysql_close($con);
function save_var($var) {
$var_str = var_export($text, true);
$var = "<?php\n\n\$$text = $var_str;\n\n?>";
file_put_contents('filename.php', $var);
}
function get_var()
include 'filename.php';
return $text;
}
?>
PS I think that should work only typing not tested
The database should be static. It is a one off event to create the database along with:
Tables
Indexes
Various constraints
Triggers
Stored procedures
This can be done with a SQL script.
Then the PHP stuff accessing this database only needs to use select, insert, delete or update statements - or as I prefer using stored procedures.
You are going to have a lot of headaches having multiple databases. Also I would hate to have to write a PHP script to do that each time and to administrate them.
<?php
$cons=mysql_connect("localhost","root","");
mysql_select_db("infogallery") or die('Not Connected to the data base:'.mysql_error());
?>
I write above code for connection with mysql but when i run this scripts..nothing display on the brouser...what can i do for the connection with mysql....
If nothing is displayed, then it means it succeeded. Add more code which queries the database and displays some results.
Don't connect as the root account. Create an account specifically for playing around with.
Once you've done that, modify your code as follows:
$cons = mysql_connect('localhost', 'username', 'password');
if ($cons === FALSE) {
die("Failed to connect to MySQL: " . mysql_error());
}
mysql_select_db(etc.....);
You don't check if the connection failed, then try to do a database operation on that potentially failed connection. The or die(...) you have will only show the error caused by the select attempt, and the error message from the failed connection will be lost.
I like to just do
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("infogallery") or die(mysql_error());
echo "So far, so good.";
How about something like the following:
<?php
try {
$cons = mysql_connect("localhost","username","password");
} catch ($e) {
die('Failed to connect to the database: ' . mysql_error());
}
try {
mysql_select_db("infogallery", $cons);
} catch ($e) {
die('Failed to select the database: ' . mysql_error());
}
?>