...

Hi! I’m Starx

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

is 'user_id' a keyword in $_SESSION['user_id']?

Sattar_kuet.bd’s Question:

I have studied the following code:

$this->user_id = $_SESSION['user_id']=$user->id;

but $_SESSION['user_id'] this does not make any sense to me. ‘user_id’ inside $_SESSION[] is not any name attribute or input field name. So is user_id is a keyword reserved in php? if so what is the significance of this keyword?

$_SESSION are super global variables which store values in SESSION and can be accessed like arrays. So user_id is just an index of a value in Session not a reserved keyword.

On the following statement

$this->user_id = $_SESSION['user_id']=$user->id;

Value from $user -> id is stored in two places (1) $this -> user_id and (2) $_SESSION['user_id']

Just like user_id a session can hold any random indices. For example

$_SESSION['asdfsafasfsadfasd'] = 'aasfsafasfasfasfasf';
Read more

Sleep() Function not doing what I think it should

HondaKillrsx’s Question:

First, correct me if i’m wrong but i’m under the assumption that when you run the Sleep() function, it pauses running the script where it is located in the script, not at the beginning. If that is true can someone tell me why the below script waits 5 seconds and then shows both echos at the same time. NOT echo the first statement on page load and then wait 5 seconds and then fire the second echo….

      echo "Your account username has been updated, you will now be redirected to the home page!";
      sleep(5);
      echo "REDIRECT!";

In your code PHP execution will pause for 5 seconds but it will not render itself part by part. i.e. It will not show the first statement and then the second. PHP keeps all its value in output buffer and display them when its finishes execution.

What happens is, it holds the value of first echo in output buffer and then waits for 5 seconds, then is holds another echo output in output buffer and shows all at once.

What you are trying to do is a lot easier in JS.

echo "Your account username has been updated, you will now be redirected to the home page!";
echo "<script> document.setTimeout(function() { document.location('redirect.html'); }, 5000); </script>";
Read more
July 13, 2013

What are the differences between group and layer in KineticJs

Hussein Amb’s Question:

I am developing a HTML5 web application using KineticJS. I read that in KineticJS there are grouping and layering. As far as I know there are no differences between them. Can you tell me the differences?

Groups are simply group of elements or objects can be stacked in any way normally within a layer.

Layers are different Canvas area that can be added on the stage.

Also you can display multiple groups at once but you cannot display multiple layers . Only the topmost layer is visible.

Read more
July 10, 2013

How to write mysql query into PDO

Latitude Brace’s Question:

Appreciate if you could help me to write below mysql code to PDO statement.

     $sql  = "SELECT * FROM node WHERE node_name='$nodename'";

     $result = mysql_query($sql);

when I read on PDO::query Manual i found this code

      <?php
      $connection = new pdo("sqlite:file.sq3");
      $query="SELECT * FROM table";
      $result = $connection->query($query);
      $row = $result->fetch(PDO::FETCH_ASSOC);
      print_r($row);
      ?>

what is the function for “sqlite:file.sq3” and “(PDO::FETCH_ASSOC)”

you connect to the database like this :

try {
$db = new PDO("sqlite:file.sq3");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
       echo 'Error : <br>' . $e->getMessage();
}

PS: You dont need the try and the catch, but we used to get the error and handle it in a nice way as we want to

and next we query like this :

 $db->query(SELECT * FROM node WHERE node_name='$nodename'");

and we fetch it like this :

 $query = $db->query(SELECT * FROM node WHERE node_name='$nodename'");
 $row   = $query->fetch(PDO::FETCH_OBJ);

and now you use $row->name for example

here is more about PDO::FETCH

  • PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set

  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

  • PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were
    bound with the PDOStatement::bindColumn() method

  • PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the
    class. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g.
    PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class
    is determined from a value of the first column.

  • PDO::FETCH_INTO: updates an existing instance of the requested class, mapping the columns of the result set to named properties in
    the class

  • PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed

  • PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

  • PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set

That line points to your sql file, there is no function for it. It opens a PDO connection and you can query further.

$connection = new pdo("sqlite:/path/to/sql/file.sq3");

PDO::FETCH_ASSOC tells the function fetch() to pull associative array from table.

Read more
July 8, 2013

CSS Transitions Not working after toggleClass()

85Ryan’s Question:

I created a toggle-menu, like the DEMO.

I add a css transition effect for div.nav-menu , and i used max-height:0; to max-height:480px; .

When click the menu toggle to show the menu, the transition was working good. But when I click the menu toggle to hide the menu again the transition didn’t work now.

What did I did wrong?

You are wrong about CSS Transitions. They do not animate when you add or remove class, It will only animate when you change the CSS properties. And You are directly adding and removing classes.

Here is your solution:

$( '.menu-toggle' ).on( 'click', function() {       
    if(nav.hasClass('toggled-on')) { 
         menu.css('maxHeight', 0); 
       //^ Here is changed the 'max-height` first so that the 
       //  Transition animation will trigger first
    } 
    nav.toggleClass( 'toggled-on' ); //Then only I toggled the class
} );

Updated Fiddle

Read more
July 5, 2013

Get id + additional string through jQuery to activate CSS3 transition

LimitBreaker15’s Question:

What am I doing wrong here?
I’m trying to get the id of the hovered div through the class, then add the string ‘-slide’ to activate the supposedly sliding transition for each .content.

<html>
<head>

<script>
$('.try').hover(function() {
    $(this.id + '-slide').css('right','0px');
});
</script>

<style>
.try {
    width: 50px;
    height: 50px;
    border: 1px black solid;
    margin-bottom: 5px;
 }

.content {
    width: 100px;
    height: 100%;
    background-color: grey;
    position: fixed;
    top: 0;
    right: -50px;
    transition: all 1s ease;
}
</style>

</head>
<body>
<div id="one" class="try"></div>
<div id="two" class="try"></div>
<div id="three" class="try"></div>
<div id="one-slide" class="content"></div>
<div id="two-slide" class="content"></div>
<div id="three-slide" class="content"></div>
</body>
</html>

Try this:

$(".try").hover(
  function () {
    $('#' + this.id + '-slide').css('right','0px');
  },
  function () {
    $('#' + this.id + '-slide').css('right','-50px');
  }
);

FIDDLE DEMO

To select a particular element in jQuery you need # for id and . for classes just like css.

You probably need this

$("#" + this.id + '-slide').css('right','0px');
Read more

PHP foreach multiple results

User2553099’s Question:

I´m not an advanced php coder so I need some help here.

I´m trying to echo list items with a link pointing to the full image and the thumnail.

This is the desired result:

<li>
    <a href="fullimagepath1">
        <img src="thumnailpath1" />
    </a>
</li>
<li>
    <a href="fullimagepath2">
        <img src="thumnailpath2" />
    </a>
</li>
<li>
    <a href="fullimagepath3">
        <img src="thumnailpath3" />
    </a>
</li>
...

This is the code I’m using

    <?php
        $images = rwmb_meta( 'product_gallery', 'type=image&size=press-thumb' );
    $fullimages = rwmb_meta( 'product_gallery', 'type=image&size=productfull-thumb' );
            foreach ( $fullimages as $fimages)
            foreach ( $images as $image)
                {
                    echo "<li><a class='thumb' href='{$fimages['url']}'><img src='{$image['url']}' /></a></li>";

    } ?>

The problem is that I’m getting the thumbnails but multiplied by the number of real results. If I have 3 thumbnails for my gallery the result will be 9 thumbnails, if I have 5 will get 25.

How can I fix the code?
Thanks in advance!

This is because of this line foreach ( $fullimages as $fimages) which is triggering inner loops.

Since you probably have 3 images and both array hold three items array, loop will run 3 times inside a bigger loop which will also execute 3 times. So you have 9 items.

On your code

foreach ( $fullimages as $fimages) //Because of this loop next statement executes
foreach ( $images as $image) {
  echo "<li><a class='thumb' href='{$fimages['url']}'><img src='{$image['url']}' /></a></li>";
}

What you probably want is?

foreach ( $fullimages as $k => $fimages) {
                      // ^ Get the index of the array
  echo "<li><a class='thumb' href='{$fimages['url']}'>
       <img src='{$images[$k]['url']}' /></a></li>";
                       // ^ Use that key to find the thumbnail from $images array
}
Read more

$.ajax: Unable to produce the error if data is 0

User1739825’s Question:

Please advise as I am new to jQuery.
The following code is:

function get(database)
    {   
        var dbValue = database; 
        console.debug("dbvalue read as :", dbValue)
        $.ajax// use of jQuery here
            ({
                type: "POST",
                url: "testconnect.php",
                data: {nameDB: dbValue},
                success: function(data)
                { 
                    alert("Successfully login and connected");
                }
                error: function(data) 
                {
                    alert("Unsuccessfully login and connected");
                }
            });
    return false;
    }

If the data is is 1(true), alert will show “Successfully login and connected”. But what if the error is 0, it cannot produce “Unsuccessfully login and connected”.

error: function() {} will trigger if there is an error in the AJAX request. If the AJAX request does not succeed then only this function will execute.

You can do what you are trying to by comparing the output on your success function, like this:

success: function(data) { 
   if(data == '1') alert("Successfully login and connected");
   else alert("Unsuccessfully login and connected");
}
Read more

how to assign window.setTimeout to dynamic variable?

Tomas Šivickas’s Question:

I need to assign window.setTimeout to dynamically made GLOBAL vars or objects, something like:

$n = 1
var variable[$n] = window.setTimeout( function () { /*somecode*/ },2000)

This isn’t working.
Also not working:

var eval(variable+$n) = window.setTimeout( function () { /*somecode*/ },2000)

But works without “var”, but I need global variable so I need with “var” scope.

What could be possible solution?

To address a global variable, you should not use var. Using var redefines the variable in that scope.

Let me explain to you with a different example:

var i = 2; 

function show() {
   alert(i); // This will show 2
}

But in this example:

var i = 2;

function show() {
   var i = 4; //This defines a local variable called "i" to be used inside function only
   alert(i); // Will show 4;
}
alert(i); // But this will still show 2

So, use it without the var

$n = 1
variable[$n] = window.setTimeout( function () { /*somecode*/ },2000)
Read more

Strange append issue

Slim’s Question:

I have this code:

HTML:

<div class="formElement" id="debtors">
    <label> Debtors</label>
    <input type="text" name="debtors">
    <button id="btnClicker" onclick="test()">Append list items</button>
</div>

and jquery:

test= function(){
    var clicked = 0;
    $("#btnClicker").click(function(){
        clicked++;
        $("#debtors").append("<input type="text" name="test"+clicked+"" value="test" />");
      });                       
};

JS fiddle here

The problem is that when the function is executed the input box is not shown at the 1st click and after the 2nd click there are 2 input boxes added and after few more clicks the boxes are duplicated for a strange reason. I tried almost everything that I found online, but it seems that I’m still new in jquery. I’m opretty sure that I’m missing something small. Do you have any fix ideas?

You can also remove the .click() from your JS code

test = function () {
    var clicked = 0;
    clicked++;
    $("#debtors").append("<input type="text" name="test" + clicked + "" value="test" />");
}

or remove onclick="test" and keep you .click() script.

To know reason check jQuery.click() vs onClick.

Because your event handler does not applies until the user clicks at the button. The onclick="test()" on your code execute the function test() which later holds event handler.

You do not need a function on variable test just remove them.

var clicked = 0;
$("#btnClicker").click(function(){
    clicked++;
    $("#debtors").append("<input type="text" name="test"+clicked+"" value="test" />");
});

Demo

Read more
...

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