...

Hi! I’m Starx

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

How to make a link appear as a normal link in one screen size, as a button in another?

Annoyingnewbie’s Question:

I’m programming a website with three different sizes for desktop, netbook and mobile phone systems.

On the main page I have a click-thru html link of the

<a href="more.html">Find out more</a> 

variety.

What I want is to change this to a button for mobile screens, like a conditional statement or something.

Any ideas?

Thanks

Use media queries. They can help you target type of screen and based on its width. For example

@media only screen and (min-device-width: 300px) and (max-device-width: 480px) {

    /* Now you can write a different style of elements on a screen with maximum 300px as width */

   a {
      color: #f00; /* Make link appear red on mobile screen */

      /* make it should like a button */
      border: 1px #c00 solid;
      background: #ddd; 
   }
}

Note: Media Queries are CSS3 features, and will not work in earlier version of IE.

Read more

Need to know if mysql query can get this type of result

Sravis’s Question:

I have a Table structure like below

+--------+---------+
| cat_id | user_id |
+--------+---------+
|     10 |       1 |
|     10 |       2 |
|     11 |       3 |
|     11 |       4 |
+--------+---------+

I’m trying to get the result like below

Array
(
    [cat_id] => 10,
    Array
    (
        [user_id] => 1,
        [user_id] => 2
    )
)

Array
(
    [cat_id] => 11,
    Array
    (
        [user_id] => 3,
        [user_id] => 4
    )
)

I tried using group it didn’t work, If i try with sub query i get error message “Subquery returns more than 1 row.”

Is it possible to achieve this kind of result using mysql query?

No, MySQL api funcions provide a result set of your records. They cannot customize to your requirements. You have to create your own functions to develop that format.

Start by getting unique category id and they go through them in a loop to get there remaining details.

$mainArray = []; //Create a array to store the records
$result = mysqli_query($conn, "SELECT DISTINCT('cat_id') as catid FROM `yourtable`");
while($row = mysqli_fetch_assoc($result)) {       

    //Now another query to fetch the users
    $res = mysqli_query($conn, "SELECT * FROM `yourtable` WHERE cat_id='$row[0]'");

    $users = array(); //array to store users
    while($r = mysqli_fetch_assoc($res)) {
         $users[] = $r['user_id'];
    }

    // Now add to your main array
    $mainArray[] = array('cat_id' => $row['catid'], "users" => $users);
}
var_dump($mainArray);
Read more

Create subset of php array and convert to json

Dilettante’s Question:

This is one of those that should be easy. I’m not even sure if “subset” is the right way to describe it.

My initial array looks like this:

array(3) { [0]=> array(5) { ["id"]=> string(1) "1" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 01:58:48" ["created"]=> string(19) "2013-05-15 01:58:48" } [1]=> array(5) { ["id"]=> string(2) "11" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "45" ["date"]=> string(19) "2013-05-15 03:34:59" ["created"]=> string(19) "2013-05-15 03:37:01" } [2]=> array(5) { ["id"]=> string(2) "25" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 22:47:46" ["created"]=> string(19) "2013-05-15 22:52:02" } } 

I’d ultimately like to end up with just the date and price values, swap them so that date is first in the array, reformat the date, and convert it to a json array that looks something like this:

[{"date":"Mar. 15","price":"50"},{"date":"Mar. 15","price":"45"},{"date":"Mar. 15","price":"50"}] 

I ran a foreach statement to get at the data and reformat the date, then went out of my league with splice, unset, and other functions that took me in the wrong direction. Any ideas?

Create a quick function to create another array with only selected elements:

function datePriceToJson($array) {
   $a = array();
   foreach($array as $i => $a) {
      $a[] = array("date" => $a['date'], "price" => $a['price']); //Creae a new array based on the one you want
   }
   return json_encode($a);
}

datePriceToJson($array);
Read more
May 15, 2013

jquery fade in, fade out loop

Hcx’s Question:

I want to create a loop like this,

anim = function () {
    $('.a1').fadeOut(function () {
        $('.b1').fadeIn(function () {
            $('.b1').delay(5000).fadeOut(function () {
                $('.a1').fadeIn(function () {
                    setTimeout(anim, 2000);
                });
            });
        });
    });
};

setTimeout(anim, 2000);

but after one loop .b1 is not fade in again so what could be the problem? or is there a better way to do this?

setTimeout() executes the function once, you are looking for setInterval()

Read more

HTML tags or CSS properties

K_programmer’s Question:

So I was wondering what’s better to use – HTML tags or CSS properties?

We have both HTML tags and CSS properties for same purpose in various cases, like in <img> tag one can use width and height html values to assign them or can use css properties for same purpose.

Then, to center some text, or some other contents too, one can use <center>Some text here</center> or css property text-align:center;

To make some text italic, one can use <i> or <em> html tag or use equivalent css properties. (Though <i> has a different meaning in HTML5, but still it’s used.)

There are many similar cases. So, what’s more acceptable and better to use?

In this age of HTML5, I would opt to not use any HTML attributes that were already marked deprecated for its predecessors HTML 4.01 and XHTML, such as width, border, height etc.

For layout, use CSS, for semantics, use HTML. The border attribute serves no other purpose nowadays than enable legacy IE5.5 sites to still work.

As for the questions about <i> and <b> I’d recommend reading up a bit on why you should only write semantic HTML, for example here.

More general reading about why HTML is not for layout/presentation can even be found on Wikipedia.

This topic is quite debatable in my opinion. HTML tags and its attributes have a semantic meaning behind it where as CSS is entirely focused on the layout and styles. HTML5 adds a new brand semantic tags.

Tags like <strong> have much more meaning then font-weight:bold. The css property only makes the text appear bold, but the HTML tag <strong> strengthens the content (You can see the difference through a text reader).

However, new generation of web focuses more on the style than on the HTML structure, so there is not a fixed rule on how it should be followed. So I suggest concentrating one factor and that is manageability. Select the option which you can manage and maintain easily.

Read more

How CSS float works? Why height of the container element doesn't increase if it contains floated elements

Boy Pasmo’s Question:

I would like to ask on how height and float works. I have this outside Div and an inner Div that has content in it. It’s height my vary depends on the content of the Inner Div but It seems that my inner div will overflow with it’s outside Div. What would be the proper way to do it? Any help would be much appreciated. Thanks!

<html>
<body>
<div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>
</body>
</html>

The floated elements do not add to the height in the container element, and hence if you don’t clear them, container height won’t increase…

I’ll show you a pictorial way

enter image description here

enter image description here

enter image description here

More Explanation:

<div>
  <div style="float: left;"></div>
  <div style="width: 15px;"></div> <!-- This will shift 
                                        beside the top div, why? because the top div 
                                        is floated to left, and hence making the 
                                        rest of the space blank -->

  <div style="clear: both;"></div> 
  <!-- Now in order to prevent the next div to float besides the top ones 
       we use `clear: both;`, this is like a wall, so now none of the div's 
       will be floated after here and also the container will now count the 
       height of these floated divs -->
  <div></div>
</div>

My other answer here will explain you why we clear, though I’ve explained it here too

You can also add overflow: hidden; on container elements, but I would suggest you to use clear: both; instead.

Also if you might like to self clear an element you can use

.self_clear:after {
  content: "";
  clear: both;
  display: table;
}

Its because of the float of the div. Add overflow: hidden on the outside element.

<div style="overflow:hidden; margin:0 auto;width: 960px; min-height: 100px; background-color:orange;">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>

Demo

Read more

How to import all classes within filesystem in php?

J Moore’s Question:

The folder structure is like so:

/main.php
  /lib/class1.php
  /lib/class2.php
  /lib/class3.php

I want to have main.php make available all the classes in lib without doing a ton of require/include. Is this possible? Is it possible to just include all files within a directory?

Create an autoloading function to load the class directly from your URL

function __autoload($class_name) {
    include "/lib/".$class_name . '.php'; //Add your folder structure like this
            // ^ Change the path to your specific need
}

//Then Simply
$class1_object = new Class1(); 
Read more

I don't know why my variables are getting these values

User1552308’s Question:

public int Gauss_Jordan(double[][] matrix, int numOfRows, int numOfCols) {
    for (int col_j = 0; col_j<numOfCols; col_j++) {
        row_i = nonzeros ++;
        System.out.println(row_i+" and "+nonzeros);
    }
    //return matrix;

    return 0;
}

up above in the method called “Gauss_Jordan”, you can see a for loop where it iterates until a certain condition is met. (duh.. lol sorry).

so i set row_i = nonzeros++ but here’s the thing, when I print out each iteration i get

  • 0 and 1,
  • 1 and 2,
  • 2 and 3

. I would expect the output to be:

  • 1 and 1,
  • 2 and 2,
  • 3 and 3.

How come this is not the case?

If pre-increment is not what you wanted. Check the initialization of nonzeros and change it into ‘1` for it to show up as you want. Your codes are functioning as they should.

Read more
May 13, 2013

Is there a way to perform binary math on binary strings in PHP?

Skyline969’s Question:

I’m working with some numbers that would be far too large for PHP to handle (IPv6 addresses in binary), so to work around this I’ve formulated a function to convert the addresses to/from binary strings (literally just a string of 1s and 0s). However, when it comes to subnet calculations the easiest way I know how to do this is to use binary math. I have no idea how I’d use binary math in this instance since I’m technically dealing with strings, not binary numbers. Is there any way I can do binary math with a string representation of a binary number?

How about going simple and converting binary to decimal then performing operations on it, then changing it back to binary?

Reference: bindec(), decbin()

Simple Example:

$a = 110;
$b = 101;

$add = bindec($a) + bindec($b);
$binadd = decbin($add); //after done change it back
Read more

PHP: clear a text file if it exceeds 50 lines

ToxicMouse’s Question:

OK, what am I missing? I am trying to clear a file if it exceeds 50 lines.

This is what I have so far.

$file = 'idata.txt';
$lines = count file($file);
if ($lines > 50){
$fh = fopen( 'idata.txt', 'w' );
fclose($fh);
}
$file = 'idata.txt';
$lines = count(file($file));
if ($lines > 50){
$fh = fopen( 'idata.txt', 'w' );
fclose($fh);
}

You have an error in your syntax, it should be count(file($file)); Using this method is not recommended for larger file as it loads the file onto the memory. Thus, it will not be helpful in case of large files. Here is another way to solve this:

$file="idata.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  if($linecount > 50) {
      //if the file is more than 50
      fclosh($handle); //close the previous handle

      // YOUR CODE
      $handle = fopen( 'idata.txt', 'w' ); 
      fclose($handle);  
  }
  $linecount++;
}
Read more
...

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