...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
June 2, 2013

apache_request_headers() versus $_SERVER

User1032531’s Question:

As far as I can tell, apache_request_headers() provides the same information as $_SERVER, but with slightly different keys. Why should someone ever use apache_request_headers() and not just get this information from $_SERVER? I am operating PHP 5.3.18 with Apache on Centos. Thank you

EDIT. identical data from $_SERVER and apache_request_headers()

Jun  2 08:50:53 localhost httpd: HTTP_HOST: www.badobe.com
Jun  2 08:50:53 localhost httpd: Host: www.badobe.com
Jun  2 08:50:53 localhost httpd: HTTP_USER_AGENT: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
Jun  2 08:50:53 localhost httpd: User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
Jun  2 08:50:53 localhost httpd: HTTP_ACCEPT: */*
Jun  2 08:50:53 localhost httpd: Accept: */*
Jun  2 08:50:53 localhost httpd: HTTP_ACCEPT_LANGUAGE: en-US,en;q=0.5
Jun  2 08:50:53 localhost httpd: Accept-Language: en-US,en;q=0.5
Jun  2 08:50:53 localhost httpd: HTTP_ACCEPT_ENCODING: gzip, deflate
Jun  2 08:50:53 localhost httpd: Accept-Encoding: gzip, deflate
Jun  2 08:50:53 localhost httpd: HTTP_REFERER: http://www.badobe.com/demo/administrator/index.php?cid=3
Jun  2 08:50:53 localhost httpd: Referer: http://www.badobe.com/demo/administrator/index.php?cid=3
Jun  2 08:50:53 localhost httpd: HTTP_COOKIE: PHPSESSID=feg3ecd4rsefvd03mgg6qear21
Jun  2 08:50:53 localhost httpd: Cookie: PHPSESSID=feg3ecd4rsefvd03mgg6qear21
Jun  2 08:50:53 localhost httpd: HTTP_CONNECTION: keep-alive
Jun  2 08:50:53 localhost httpd: Connection: keep-alive
Jun  2 08:50:53 localhost httpd: HTTP_IF_MODIFIED_SINCE: Sun, 02 Jun 2013 15:48:42 GMT
Jun  2 08:50:53 localhost httpd: If-Modified-Since: Sun, 02 Jun 2013 15:48:42 GMT
Jun  2 08:50:53 localhost httpd: HTTP_CACHE_CONTROL: max-age=0
Jun  2 08:50:53 localhost httpd: Cache-Control: max-age=0

Because apache_request_headers() returns an associative array of all the HTTP headers in the current request, where as $_SERVER gives more than that

  • header details
  • path details
  • script locations
Read more
June 1, 2013

jQuery Scroll to top fade in/out issue

Xavier’s Question:

This code has two parts:

The first one is supposed to fade in the .toTop button when the user scrolls down and keep it hide otherwise.

The second part is supposed to bring the user top when clicking on it.

Part two isn’t working when mixed with part one. I can’t find the conflict between the two.

<script>
    $(document).ready(function(){

        $(".toTop").hide();

        $(function () {
            $(window).scroll(function () {
                if ($(this).scrollTop() > 300) {
                    $('.toTop').fadeIn();
                } else {
                    $('.toTop').fadeOut();
                }
            });        
        });        
    });

        var easing, e, pos;
    $(function(){
      $(".toTop").on("click", function(){
        pos= $(window).scrollTop();
        $("body").css({
          "margin-top": -pos+"px",
          "overflow-y": "scroll", 
        });
        $(window).scrollTop(0);
        $("body").css("transition", "all 1s ease");
        $("body").css("margin-top", "0");
        $("body").on("webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd", function(){
          $("body").css("transition", "none");
        });
      });
    });      
</script>

Use this…

$(document).ready(function(){

        $(".toTop").hide();

        $(function () {
            $(window).scroll(function () {
                if ($(this).scrollTop() > 200) {
                    $('.toTop').fadeIn();
                } else {
                    $('.toTop').fadeOut();
                }
            });        
        });        
    });

var easing, e, pos;
    $(function(){
      $(".toTop").on("click", function(){
        pos= $(window).scrollTop();
        $("body").css({
          "margin-top": -pos+"px",
          "overflow-y": "scroll", 
        });
        $(window).scrollTop(0);
        $("body").css("transition", "all 1s ease");
        $("body").css("margin-top", "0");
        $("body").on("webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd", function(){
          $("body").css("transition", "none");
        });
      });
    });

And dee this DEMO

First point is that, you have used to many .ready() event handler. Remove all the redundancies:

$(document).ready(function(){

  $(".toTop").hide();

  $(window).scroll(function () {
      if ($(this).scrollTop() > 300) {
           $('.toTop').fadeIn();
      } else {
           $('.toTop').fadeOut();
      }
  });        

  var easing, e, pos;
  $(".toTop").on("click", function(){
    pos = $(window).scrollTop();
    $("body").css({
      "margin-top": -pos+"px",
      "overflow-y": "scroll", 
    });
    $(window).scrollTop(0);

    $("body").css("transition", "all 1s ease");
    $("body").css("margin-top", "0");
    $("body").on("webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd", function(){
      $("body").css("transition", "none");
    });
  });

});
Read more
May 31, 2013

javascript or jquery : mouse events

VJS’s Question:

Need your help in understanding this code..Is this Javascript ( expression language ) or JQuery. I tried to understand but didn’t get it.

var interval = 0, changed = false;
...............
...............

var start = function () {
    $(document).on('mousedown mousemove scroll touchstart touchmove keydown', change);
    setInterval(check, 1000);
};

 var change = function () {
    changed = true;
};

var check = function () {
   console.log("changed .....");
};

start();

Basically I want to do something ( business logic ) if user had performed some events on browser.Got this code on net and felt like something this is doing the same what i want.

This following part is jQuery specific, all other are pure JavaScript.

$(document).on('mousedown mousemove scroll touchstart touchmove keydown', change);

This is a event handler of jQuery which is calling a native javascript function change().

Notes:

  • To run the jQuery part you need to import jQuery Library from their site.

  • You can identify the jQuery selectors by user of $ infront. ($ does not always means jQuery)

Read more

Calling ajax once

User2310422’s Question:

I have created a button on my website when it is clicked, I sent data on some php file using ajax and return the results. The code I am using is below,

My Goal :

  1. When that button is clicked for the first time. I want to send the data on some php file using ajax and return the results, and
  2. When it is clicked for the second time, I just want to hide the content, and
  3. When it is clicked for the third time, I just want to show the container without calling the ajax again.

jQuery:

$(function() {
    $('#click_me').click(function(){
        var container = $('#container').css('display');
        var id = $('#id').html();
            if(container == 'none'){
                $.ajax({
                type: 'POST',
                data: {id: id},
                url: "ajax/get_items.php",
                }).done(function(data) {
                $('#container').html(data);
                }).success(function(){
                $('#container').show('fast');
                });
                }else if(container == 'block'){
        $('#container').hide('fast');
        }
        });
});

Html :

<input type="button" id="click_me" value="Click Me"/>
<div id="container"></div>

You can do this by defining a simple variable counting the clicks.

$(function() {
    var clickCount = 1; //Start with first click

    $('#click_me').click(function(){
        switch(clickCount) {
             case 1: //Code for the first click

                 // I am just pasting your code, if may have to change this
                 var container = $('#container').css('display');
                 var id = $('#id').html();
                     if(container == 'none'){
                         $.ajax({
                         type: 'POST',
                         data: {id: id},
                         url: "ajax/get_items.php",
                         }).done(function(data) {
                         $('#container').html(data);
                         }).success(function(){
                         $('#container').show('fast');
                         });
                         }else if(container == 'block'){
                 $('#container').hide('fast');
                 }
              break;
              case 2: 
                 //code for second click
                 break; 
              case 3:
                 //Code for the third click
                 break;      
        });
        clickCount++; //Add to the click.
});
Read more

Can I select a update from database field

Ramin Rahimi’s Question:

What I am trying to do is to select a update from a portion of my site where users upload pictures and I know I have to create a field for that in my database but first I was wondering to know if I can use this syntax like:

SELECT UPDATE 
FROM photos 
WHERE album LIKE BINARY 'loggedin_avatar'  
ORDER BY datemade ASC

so is this a right syntax? also where can I learn about filtering the files being uploaded to my site. Generally filtering the files being uploaded.

No, that is not the correct syntax. SELECT and UPDATE are two different query statements.

If you trying to select a field called update from your database table, then you have to quote them

SELECT `update` FROM photos WHERE album LIKE BINARY 'loggedin_avatar' ORDER BY datemade ASC"; 

If you are trying to select a updated row after updating them, you have to send mulitple statements.

  • First update the rows
  • Select the updated row which the help of a primary key field.
Read more
May 30, 2013

PDO – get two select values into an array

NojoRu’s Question:

I have this PDO:

$id = 1;
$title = 'resourceName';
$url = 'resourceURL';
$result = array($title => $url);

include('../dbconnect.php');

$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare("SELECT resourceName, resourceURL FROM Resources WHERE categoryID = :id");
$stmt->bindParam(':id', $id);
$stmt->execute(array_values($result));
$row = $stmt->fetchAll();
print_r($row);

I am just getting this error:
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

How can make the PDO result be an array where resourceName is the key and resourceURL is the value?

You are binding unneeded parameters to the query.

$stmt->bindParam(':id', $id);
$stmt->execute(array_values($result)); //On this line. These parameters are 
                                         not needed

Let me explain

$stmt->bindParam(':id', $id);

Binds the value of $id to the SQL Parameter :id and Again

$stmt->execute(array_values($result));

You are binding another parameters without any indexes.

Thus your query wants 1 parameter and you are sending two paramters.

Solution: Use one of them

Either

$stmt->bindParam(':id', $id);

Or , directly like this

$stmt->execute(array(":id" => $id));

After, that get columns from the rows and convert them into a new array in your required format

$row = $stmt->fetchAll();
//Now assuming only one was returned from the database this might work
$new = array($row[0] -> resourceName => $row[0] -> resourceURL);
Read more

Javascript not checking whether a checkbox was selected or not

User2437473’s Question:

I’m trying to build a quiz with multiple choice questions, one of which has multiple correct answers. So I’m trying to check which checkboxes in my questions have been selected by a student in order to give the right feedback. my code is:

for(var i = 0; i< input1.length; i++)
    {
        if(input1[0].checked && input1[1].checked)
        {
        submit_answer.onclick = showFeedback1; 
        }
        else
        {
        submit_answer.onclick = false1; 
        }
    }

It never takes the first if, even if I select those two only. No matter what I put in the if statement, it only takes the else.

and this is just a part of my .js

var quiz = document.getElementById('quiz');

var questions = quiz.getElementsByTagName('p');

input1 = questions[0].getElementsByTagName('input');

var submit_answer = document.getElementById('submit_answers'); // this is the submit button

I cannot make proper assumption of what you are trying to do.

FIRST PROBLEM

Your for loop is incrementing on 1, so on the each next iteration it is comparing using same previously used value.

SECOND PROBLEM

Your structure is horrible, your script fetches up all the input elements inside every p. You should properly organize your element in groups and then match whether or not they are checked.

Read more

Warning: mysql_result() expects parameter 2 to be long, string given in

Vicente Carlos’s Question:

newbie here…

I need some help or a solution to the following error please.

Warning: mysql_result() expects parameter 2 to be long, string given in /home/username/public_html/shop/admin/includes/th.inc.php on line 1036

CODE:

<?php
    $sql = "SELECT description from affiliSt_themes WHERE title = 'default' LIMIT 1";
    $thisDesc = mysql_result(mysql_query($sql, $databaseConnect), '');
?>

Greatly appreciated.

Here is your answer:

$thisDesc = mysql_result(mysql_query($sql, $databaseConnect), '');
   //                                                         ^ Remove this, OR USE LONG VALUE
Read more
May 29, 2013

Using margin on wrap list won't work. margin: top is always 0

Vibskov’s Question:

http://jsfiddle.net/MqPDH/10/

Why does the 1st wrap .wp-list margin: 10px and .a .b use margin: 10px not work?

.wp{
    background-color: blue;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    left: 0;
    right: 0;
    width: 450px;
}
.wp_list{
    background-color: red;
    margin: 10px;
    height: 130px;
    position:relative;
}
.a, .b, .c{
    background-color: gray;
}
.a{
    width: 220px;
    height: 30px;
    margin: 10px;
}
.b{
    width: 220px;
    height: 100px;
    margin: 10px;
}
.c{
    width: 130px;
    height: 130px;
    top:0;
    right:0;
    position:absolute;
}

HTML:

<div class="wp">
    <div class="wp_list">
        <div class="a">a</div>
        <div class="b">b</div>
        <div class="c">c</div>
    </div>
    <div class="wp_list">
        <div class="a">a</div>
        <div class="b">b</div>
        <div class="c">c</div>
    </div>
    // generate from php
</div>

Margins collapse on block elements, this means that when you have an element with a 10px margin set on the bottom, followed by an element with 5px margin set on the top. The margin between the two will not be 15px, but will collapse down to the largest of the two: 10px, or in this case when they’re both 10px, it will collapse to be 10px.

You should add display: inline-block; to .a, .b, .c, that will fix it:

.a, .b, .c{
    background-color: gray;
    display: inline-block;  
}

jsFiddle

This is mainly because because it is behaving as inline element. Add display: inline-block;

.wp_ist{
    display: inline-block;
    background-color: red;
    margin: 10px;
    height: 130px;
    position:relative;
}
Read more
...

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