Showing posts with label mysql. Show all posts
Showing posts with label mysql. Show all posts

Tuesday, June 21, 2011

Save image in database(MySQL & Blob datatype)


Hi,

This is rather interesting topic, but is among the simpler one's. In this I will show how to save an image in its actual format in the database as data and fetching it as an image to the web page. First of all create a database table and assign "blob" data type to the fields that will hold the image. Here is the schema for the database table that I am using:

CREATE TABLE `employees` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`empname` VARCHAR(50) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
`profile_pic` LONGBLOB NULL,
`ext` VARCHAR(5) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
PRIMARY KEY (`id`)
)

[You can find the entire source code here]

Now that my table is ready lets move on to the HTML. It is a pretty simple one just a form with couple of fields as follows:

<form method="post" action="" enctype="multipart/form-data">
Enter Name:<br/><input type="text" name="emp_name" /><br/><br/>
Profile Pic:
<input type="file" name="pic" /><br/><br/>
<input type="submit" value="Save Image" />
</form>

The page looks something like:



After saving the data, this is what I get:


Code and Explanation:

When the form is submitted here is what I have done:


$content=file_get_contents($_FILES['pic']['tmp_name']);
$content=mysql_escape_string($content);

@list(, , $imtype, ) = getimagesize($_FILES['pic']['tmp_name']);

if ($imtype == 3){
$ext="png";
}elseif ($imtype == 2){
$ext="jpeg";
}elseif ($imtype == 1){
$ext="gif";
}

Sunday, March 20, 2011

Cakephp Store procedure + multiple resultset fetch

Hi All,


I have been working on a project which involves huge data. So the idea is to use stored procedures to make the query execution fast. Most tricky part in this, is to fetch multiple-result set from a single store procedure. 


Step 1: Write the procedure which have the multiple select queries.
Step 2 : Make a component within your cake's controller folder(app/controllers/components) and paste the code given below:

function callstoreproc($procname,$paramarr=null)
{
$connstr = ConnectionManager::getInstance();

$conhost = $connstr->config->default["host"];
$conlogin = $connstr->config->default["login"];
$conpassword = $connstr->config->default["password"];
$condatabase = $connstr->config->default["database"];

$mysqli = new mysqli($conhost, $conlogin, $conpassword, $condatabase);

if (mysqli_connect_errno())
{
echo "Connect failed";exit();
}
 $query = $procname;
 if (mysqli_multi_query($mysqli, $query))
{
$i=0;
while (mysqli_more_results($mysqli))
{
if ($result = mysqli_store_result($mysqli))
{