...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
March 14, 2012

displaying pdf files stored in myql database PHP

Question by Samer El Gendy

i am trying to display pdf files stored in mysql database in the browser when the user request to.

structure of the mysql table: 
CREATE TABLE `file` (
`id` Int Unsigned Not Null Auto_Increment,
`name` VarChar(255) Not Null Default 'Untitled.txt',
`mime` VarChar(50) Not Null Default 'text/plain',
`size` BigInt Unsigned Not Null Default 0,
`data` MediumBlob Not Null,
`created` DateTime Not Null,
PRIMARY KEY (`id`)
)
php code: 
$query = "
            SELECT `type`, `name`, `size`, `data`, `mime`
            FROM `file`
            WHERE `id` = {$id}";
        $result = $dbLink->query($query);
        if($result) {
            // Make sure the result is valid
            if($result->num_rows == 1) {
            // Get the row
                $row = mysqli_fetch_assoc($result);
                // Print headers
                header('Accept-Ranges: bytes');
                header('Content-Transfer-Encoding: binary');
                header("Content-Type: ".$row['mime']);
                header("Content-Length: ".$row['size']);
                header("Content-Disposition: inline; filename=".$row['name']);
                echo $row['data'];
            }
        }
code to save file to database:
if(isset($_FILES['uploaded_file'])) {
    // Make sure the file was sent without errors
    if($_FILES['uploaded_file']['error'] == 0) {
        // Connect to the database
        $dbLink = new mysqli('localhost', 'REDACTED',"REDACTED", 'pdfs');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ".mysqli_connect_error());
        }

        // get all required data
        $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
        $type = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
        $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file']['name']));
        $size = intval($_FILES['uploaded_file']['size']);

        // Create the SQL query
        $query = "
            INSERT INTO `file` (
                `name`, `type`, `size`, `data`, `created`
            )
            VALUES (
                '{$name}', '{$type}', {$size}, '{$data}', NOW()
            )";

        // Execute the query
        $result = $dbLink->query($query);

        // Check if it was successfull
        if($result) {
            echo 'Success! Your file was successfully added!';
        }
        else {
            echo 'Error! Failed to insert the file'
               . "<pre>{$dbLink->error}</pre>";
        }

however, when i try to view a pdf, adobe reader start loading and then i get this error massage: the file is damaged and could not be repaired.
am i doing something wrong?

Answer by Starx

Frankly, I don’t like this way at all.

KISS

Keep it Short & Simple

Whatever you are trying to do, there is better way of doing it.

  1. If security is the problem you have .htaccess and access roles
  2. If file handling is the problem you have PHP.
  3. If protected download is a problem then again with the combination of PHP and its session handling, you can do it.
  4. If viewing is the problem you have browser that.
  5. If you want to force download the file, then PHP’s header tags is enough.
Read more

javascript: add script that will be evaluated before body scripts?

Question by IttayD

I have a script foo.js that is included in <head>. Inside body I have an inline script. Inside it, I want to add to the document another script for bar.js that will be loaded and evaluated before the inline script.

<html>
  <head>
    <script src="foo.js" type="text/javascript"/>
  </head>
  <body>
    <script type="text/javascript">
      bar()
    </script>
  </body>
</html>

In foo.js I want to add a script pointing to bar.js

bar.js:

function bar() {
  alert('hi');
} 

What should be the code of foo.js?

NOTE: I know I can use onload in this trivial example. But in my real case, bar.js contains a function that is called several times and I want to be able to inline these calls in the right sections of the page (for code locality)

Answer by Rob W

You have got two options:

  1. Use document.write('<script src="bar.js"></script>') in foo.js.
  2. Dynamically create and insert a <script> element within the head (since scripts in the head have to be loaded before the rest is parsed, this works):

    !function(){
        var s = document.createElement('script'),
            currentScript = document.getElementsByTagName('script')[0];
        s.src = "bar.js";
        currentScript.parentNode.insertBefore(s, currentScript);
    }()
    

Answer by Starx

As you are doing currently, the script of the head will be evaluated at first and then the one from the body.

But when the script of head is loaded, the script inside the body will not have been loaded yet. SO the function will be unavailable to it.

So you best way I know is to use window.onload which triggers the code once every DOM elements like script are ready for manipulation.

window.onload = function() {
   bar();
}
Read more

Jquery Browser Resize center Div even on scroll

Question by Joe

I have this code…

<style type="text/css">
#container {
  width: 200px;
  height: 200px;
  background-color: #567;
}
</style>

<div id="container">
  My center div...
</div>


<script type="text/javascript">
$(window).resize(function(){
  $('#container').css({
    position:'absolute',
    left: ($(window).width() - $('#container').outerWidth())/2,
    top: ($(window).height() - $('#container').outerHeight())/2
  });
});

// To initially run the function:
$(window).resize();
</script>

This works great except if I scroll to the bottom of the page it will not center the DIV in the middle of the browser screen based on the new coordinates of where I am at in the position of the page. So my question is, if I click to open this DIV, what can I do to center the DIV if I am scrolled to the bottom of a long page?

Answer by whiteatom

Your script will only centre on the window at the top of the page.. top is relative to the document, not the window – try position:fixed and then your centring script should work.

Answer by Starx

The best way for a horizontal center is to give margin: 0 auto CSS. As for the vertical centering, you current way is good enough.

Read more

Prevent keydown() from being captured by document binding

Question by Elliot Bonneville

I’m not exactly sure how to phrase this, so I couldn’t search it. Basically, I have a keydown() bind on $(document). I’d like to show() another div, and have all keydown events be rerouted to this div and prevented from firing off in the document handler. Is this even possible, or would I have to put all my main keybindings on another div and work from there?

Answer by Jeffrey Sweeney

e.stopPropagation, or
e.preventDefault (depending on the situation)
Where e is the event.

Ex:

function onKeyDown(e) {
   doStuff();
   e.preventDefault();
}

Answer by Starx

e.preventDefault() will prevent the default behaviour of an event. What you need is to use
e.stopPropagation(), so that the event does not bubble up the DOM structure.

To read more about the difference, read this post.

$(element).keydown(function(e) {
     // do the task
     // allow the default behaviour also
     e.stopPropagation();
   //^. BUT stop the even bubbling up right here
});

e.stopProgation(), can be bit confusing to grasp on the first but I created a demo with click event to explain it.

Hope it helps!!

Read more

Adding datepicker event handler multiple times

Question by esviko

Using jQuery I’m trying to add the datepicker event handler to an input element.

    <div id="Box_tmpl" style="border:solid 1px #777; background:#ddd; display: none;">
        <a class="remove-box" href="#">remove</a>
        <div>
            <label for="PeriodStart">Period (start):</label>
            <input id="PeriodStart" class="start-end-date" name="period_start" readonly="readonly" />
        </div>
        <div>
            <label for="PeriodEnd">Period (end):</label>
            <input id="PeriodEnd" class="start-end-date" name="period_end" readonly="readonly" />
        </div>
    </div>

    <a class="add-box" href="#" style="margin: 6px 0 10px auto;">add</a>

    <div id="Boxes">
        <div style="border:solid 1px #777; background:#ddd;">
            <a class="remove-box" href="#">remove</a>
            <div>
                <label for="PeriodStart">Period (start):</label>
                <input id="PeriodStart" class="start-end-date" name="period_start" readonly="readonly" />
            </div>
            <div>
                <label for="PeriodEnd">Period (end):</label>
                <input id="PeriodEnd" class="start-end-date" name="period_end" readonly="readonly" />
            </div>
        </div>
    </div>

    <script type="text/javascript">
        $(function(){
            $('.start-end-date').datepicker({ dateFormat: "yy-mm-dd" });

            $('.remove-box').click(function(){
                $(this).parent().remove();
            });

            $('.add-box').click(function(){
                $('#Box_tmpl').clone().removeAttr('id').show().appendTo('#Boxes');
                $('.start-end-date').datepicker({ dateFormat: "yy-mm-dd" });
                $('.remove-box').click(function(){
                    $(this).parent().remove();
                });
                return false;
            });
        });
    </script>

Adding a new box works.
Adding the remove-box event handler within the new box works.
Adding the datepicker event handler withing the new box DOES NOT work. I don’t understand why…
Creating a new element using $().clone() does the new element inherit the old element’s event handlers? If it does, may be my problem is adding the datepicker event handler multiple times to the same element… I’m running out of ideas

Answer by StilgarBF

you have to use

$().clone(true)

http://api.jquery.com/clone/

withDataAndEventsA Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well.

for your question in the comment: when initializing, the datepicker adds a class “hasDatepicker” to the input. you can not reinitialize an Input with that class,
So if you want NOT to clone the events, you have to .removeClass('hasDatepicker') from your cloned input, then initialize it.

the code in your fiddle has to be changed:

$('#Box_tmpl').clone().removeAttr('id').find('input.start-end-date').removeClass('hasDatepicker').end().show().appendTo('#Boxes');
$('.start-end-date').datepicker({ dateFormat: "yy-mm-dd" });

note: .end() rewinds to the state it was until find()

Answer by Starx

In order to bind the event to the dynamically created or cloned elements use .on()

$('#Boxes').on('click', '.remove-box', function(){
   $(this).parent().remove();
});

Demo

Read more

jQuery AJAX – Creating DOM elements

Question by Kolind

I am having this function in jQuery where I’m getting new posts with AJAX and PHP. And then creating a new div and appending the post to it.

Here is my code:

function getMorePosts(latestPost){

    $.ajax({
        type: "POST",
        url: "/includes/classes/handler.php?do=getMorePosts",
        data: "&latestPost="+latestPost,
        cache: false,
        success: function(data){
            if(data){
                $('#addUpdate textarea').val('');
                $('<div id="newPosts"></div>').insertAfter('.myDeskAdd');
                $(data).prependTo('#newPosts');
            }
        }
    });
    return false;
}

Now, data is all of HTML code from my handler.php. Everything works, it’s appending and I can see the result on the screen. And it’s correct – nice!

But here is my problem:
When it’s added to the screen, it’s like I cant ‘use’ the DOM elements. For example: I have an image which I can click, and then it has to call an alert from jQuery, but it’s not. And all other jQuery effects bound to the dom elements created doesn’t work.

Those elements not working DOES work if I press F5.

I have tried html(), prepend(), append() and so on.

Answer by Shyju

for all dynamic content (loaded from ajax), bind methods using jQuery on. Then it should work

instead of this,

 $(".imageClass").click(function(){
    alert($(this).html());    
 });

Use this

 $(".yourContainerDiv").on("click", ".imageClass", function(event){
     alert($(this).html());    
 });

http://api.jquery.com/on/

Answer by Starx

When elements are dynamically generated, they will not attach to previous event handlers.

You have to use .on() method to delegate the event handlers.

Example:

$(".yourmajoreventhandler").on('click', function() {
    //do your stuff
});

Delegation Example:

$("body").on('click', ".yourmajoreventhandler", function() {
    //do your stuff
});

Now, every time, you generate a element with class yourmajoreventhandler the above function will run.

Read more

Why php divides date instead of saving it as string?

Question by robert

I have a MySQL database table that has a VARCHAR field storing a date in dd/mm/yyyy format.

I have a situation where I need to extract that date to a variable and then save it in a different table (which has a different structure than the first one).

So I do this:

$result=mysql_query("select * from shares") or die(mysql_error());
$row=mysql_fetch_array($result);
$date_old=$row['last_update'];    //date in dd/mm/yyyy format

Then when I try to insert $date_old into the other table, instead of inserting the date, PHP actually performs a mathematical division operation on it! So instead of saving 14/03/2012, it divides 14 by 3 and then by 2012 and stores 0.0023 in the database.

Surely there is a way to stop this from happening using a built-in function (without removing the slashes from the string and then putting them back in before insertion)?

Answer by Karoly Horvath

When doing insert put the values in single quotes: " ... last_update = '$date' ... ", otherwise mysql will do the calculations.

Note: for storing dates use the date type.

Answer by Starx

That is because, it turns out into an expression 14/03/2012

Escape the values using quotes.

$query = "INSERT INTO anothertable (data) VALUES('$olddate');";
Read more

img maximized in the background inside a div

Question by danielovich

I have been fiddling around with this for some time now, but I still don’t understand how it should be done.

I would like the image to be maximized (100%/100%) in the background of the itemtemplate div, but right now it just makes it fit inside the div which is 250px/250px.

<div class="itemtemplate" data-win-control="WinJS.Binding.Template">
    <img style="-ms-grid-row-span: 2;" src="#" data-win-bind="src: backgroundImage; alt: title" />
    <div class="item-overlay">
        <h4 class="item-title" data-win-bind="textContent: title"></h4>
        <h6 class="item-subtitle win-type-ellipsis" data-win-bind="textContent: subtitle">
        </h6>
    </div>
</div>

Any ideas ? thx.

Answer by Starx

I am not familiar with the attributes you are using. But, in order to use an image for the background. There are couple of ways.

  1. If it is <body> or <table> you can also define them by using doing something like this

    <body background="link/to/image.jpg">
    
  2. But the global way, which every element supports would be to define them using CSS

    <div style="background-image: url("link/to/image")">...</div>
    

Now, coming to the image part

Whenever you are using a background image,

  • It is never going to re-size to fit the container. Unless you use CSS3.

    /* CSS3 Snippet to resize a background */
    div
    {
        background-image:url("link/to/image");
        -moz-background-size:80px 60px;
        background-size:80px 60px;
        background-repeat:no-repeat;
    } 
    
  • If the container is big, it will start repeating itself to fill the area. Which can be controlled to repeat or not repeat. Like

    div { 
        background-image: url("link/to/image");
        background-repeat: no-repeat; /* similary repeat-x and repeat-y */
    }
    

However, what you are trying to use in using a <img /> to act as a background, which is semantically wrong and I do not recommend it.

Read more

Get week day name from jquery ui calendar

Question by PalAla

I want to get the name of the Day when choosing date from jquery ui calender.

for example, when choosing 14-3-2012 it should returns Wednesday.

$("input[name=date]").datepicker({
    dateFormat: 'yy-mm-dd',
    changeYear:true,
    changeMonth:true,
    onSelect: function(dateText, inst) {
         var date = $(this).datepicker('getDate');

         //what should I write here to get the day name?

    }
});

Answer by ManseUK

Create an array with the list of days in it …

var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

Then in your onselect function get the day number and use the above array to return the day of the week

onSelect: function(dateText, inst) {
  var date = $(this).datepicker('getDate');
  var dayOfWeek = weekday[date.getUTCDay()];
  // dayOfWeek is then a string containing the day of the week

}

Answer by Starx

There are various formats from which you can display the dates.

Check this for all the date formats compatible with the calendar.

In your case dateFormat: 'DD' displays the WeekDays.

$("input[name=date]").datepicker({
    dateFormat: 'DD',
    changeYear:true,
    changeMonth:true,
    onSelect: function(dateText, inst) {
         alert(dateText); // alerts the day name
    }
});
Read more

How to pass selected check-box value(s) from jQuery to PHP as an array?

Question by Zoran

UPDATED CODE:

Now, I have this code:

<h2>Testing</h2>

<input type="checkbox"  name="fruit1" id="id1"  class="box">Banana<br /><br />
<input type="checkbox"  name="fruit2" id="id2"  class="box">Cherry<br /><br />
<input type="checkbox"  name="fruit3" id="id3"  class="box">Strawberry<br /><br />
<input type="checkbox"  name="fruit4" id="id4"  class="box">Orange<br /><br />
<input type="checkbox"  name="fruit5" id="id5"  class="box">Peach<br /><br />
<form id="myForm" action="2.php" method="post">
    <input type="submit" id="groupdelete" value="clickme"><br />
</form>     

<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script>

$('#groupdelete').on('click', function(){
var names = [];
$('input:checked').each(function() {
    names.push($(this).attr("id"));

});

$.post("2.php", { "names" : names }, function(data) {
    names = names.join(",");
    // do something on success
    alert(data); //if everything is working correctly should alert the var_dump here
});
});

</script>

On page 2.php I have this:

<?php
$names = explode(",",$_POST['names']);
var_dump($names);
?>

Which prints: array(1) { [0]=> string(0) “” }

What I am doing wrong???

Zoran

Answer by Starx

Send an ajax request to the server

names.push($(this).attr("id"));

$('#groupdelete').on('click', function(e){
    e.preventDefault(); //stop the default form action
    var names = [];
    $('input:checked').each(function() {
        names.push($(this).attr("id"));
    });

    $.post("page2.php", { "names" : names }, function(data) {
        // do something on success
        alert(data); //if everything is working correctly should alert whatever page2.php echos or prints
    });

});

Update 1

JS Array and PHP array are two different things and an easy way to overcome this is join

names = names.join(","); //Join all the array with a comma nd send

Later on the PHP Script, use explode() to get your array back

$names = explode(",",$_POST['names']);
var_dump($names);

Update 2

Make the following changes on your current code

names = names.join(",");
$.post("2.php", { "names" : names }, function(data) {
    alert(data); //if everything is working correctly should alert the var_dump here
});

Update 3

I have created a fiddle, with the proper way to do it. Check it and update your codes as per.

Update 4

Ok, finally starting the get the picture now. Check this update.

Basically, create a hidden element, whose value will be updated with the checked box’s id value and send it.

Update 5

If you want to stop a field from being submitted. You can assign disabled="disabled" to stop it from being submitted.

Here is an updated fiddle

Read more
...

Please fill the form - I will response as fast as I can!