...

Hi! I’m Starx

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

mySQL previous/next query

Question by StealthRT

I am trying to figure out a way to have a previous and next button to display more data for a given query-sorta like a pagination would do.

The query is this:

$query = "SELECT * 
        FROM wp_posts p
            LEFT OUTER JOIN wp_term_relationships r ON r.object_id = p.ID
            LEFT OUTER JOIN wp_term_taxonomy x ON x.term_taxonomy_id = r.term_taxonomy_id
            LEFT OUTER JOIN wp_terms t ON t.term_id = x.term_id
            LEFT JOIN wp_postmeta pm ON p.id = pm.post_id
        WHERE p.post_status = 'publish'
        AND pm.meta_key = 'xTraData'
        AND p.post_type = 'post'
        AND t.slug = 'press-coverage'
        ORDER BY p.post_date DESC LIMIT 0,6;";

How can i get the previous id and next id to use for the next/previous buttons for refreshing the query string?

Answer by Starx

You could get them using $_GET variables, which can be sent from URL. Process them to raise you limits.

A mysql limit defines how much rows to fetch and from where to fetch.

So, 0, 6 in your query say start from 0 (first) and select 6 rows.

$p_num = isset($_GET['pagenumber']) && (int)$_GET['pagenumber'] > 0 ? $_GET['pagenumber'] : 0;
$p_size = 6;

$query = "SELECT * 
        FROM wp_posts p
            LEFT OUTER JOIN wp_term_relationships r ON r.object_id = p.ID
            LEFT OUTER JOIN wp_term_taxonomy x ON x.term_taxonomy_id = r.term_taxonomy_id
            LEFT OUTER JOIN wp_terms t ON t.term_id = x.term_id
            LEFT JOIN wp_postmeta pm ON p.id = pm.post_id
        WHERE p.post_status = 'publish'
        AND pm.meta_key = 'xTraData'
        AND p.post_type = 'post'
        AND t.slug = 'press-coverage'
        ORDER BY p.post_date DESC LIMIT ".(($p_num-1) * $p_size).",".$p_size.";";

Now, send a request like: yourpage.php?pagenumber=2 and it will query the second page where a page will hold about 6 items.

Read more

How to extract HTML tags from the web page generated at runtime

Question by shailbenq

I am using a SimpleHTMLDOM parser to extract HTML data from web pages. But I came across websites such as www.coursera.com wherein the webpage is generated at runtime.

I need to know has anyone tried parsing such pages?

I am new to this field so some theory on this topic would help my understanding in parsing webpages.

Answer by Starx

John Resig wrote an HTML Parser.

Demo: http://ejohn.org/blog/pure-javascript-html-parser/

This can workout for you.

Read more

php array to radio button

Question by user2128593

i want to create a radio button labeled with the values of my array. all i can do is to print them all. what can i use to access my array (dynamic-array) besides indexes since i will not know the order and number of files inside my languages directory? Thanks!

input

english.xml,mandarin.xml,french.xml

these files is saved at languages and i will use the file names as labels in my radio button form.

$files = glob("languages/*.xml");

foreach($files as $file){

   $file = substr($file, 10); //removes "languages/"
   $file = substr_replace($file, "", -4); //removes ".xml"
   ?>

   <p><?=$file?></p> // prints out the filename
   <?}?>

output

<form action="">
<input type="radio" name="lang" value="english">english
<input type="radio" name="lang" value="mandarin">mandarin
<input type="radio" name="lang" value="french">french
</form>

sorry for my bad english i hope i explained it well.

Answer by Starx

You can access the key of the array using foreach too. Like this:

foreach($files as $key => $value) {
    //....
}
Read more

Korean is not recognized in HTML page

Question by ProgrammingNerd

When I type Korean in my html code and open it through my browser, Korean is not recognized by the browser and prints some weird words. What shall I do?

Answer by Starx

There must be few mistakes you are making.

  • First, You should have a doctype specified on your HTML page. Use HTML5 doctype

    <!DOCTYPE html>
    
  • Second, you should specify the character encoding of the document as well. So, add:

    <meta charset="utf-8" />
    

    In your head section. Or for a longer version with better cross browser compatibility use:

    <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
    

Also as Juhana said, your file must be saved with same encoding (i.e. Unicode UTF-8) to be able to store Unicode characters and display them.

Read more

How to deal with content that will be added later in jQuery?

Question by Develop Smith

I want to control a canvas that is automatically created in the run-time.
The problem here is that jQuery function will have to deal with a content that isn’t exist when the page is ready.

$(document).ready(function(ee) {
     $("#containerInsertBtn").click(function(e) {
         e.preventDefault();
         $("#container").html("<canvas width='300' height='300' id='tk'>fall</canvas>");    
    });

    $("#tk").click(function(eg) {
        alert('tic');
    });

});

The HTML Markup:

<div id="container" contenteditable="true"></div>
<button id="containerInsertBtn">Add Canvas</button>

Answer by Starx

Your code does not work because a dynamically created element will not be included on DOM while the event handler is executed.

Your solution is event delegation. jQuery has .on() to do that.

$("body").on('click', '#tk', function(e) {
    //....
});

You need to specify a parent container to delegate the events to its child elements liek #tk

If you want to delegate to a element based on its tag name, its as same as the above.

$("body").on('click', 'canvas', function(e) {
    console.log($(this)); // you can access the active element by using $(this)
    //....
});
Read more

PHP, quotes, and .html

Question by idigyourpast

I’m having a bit of a brain fart with this one line:

jQuery("#image-div").html("<img src='get.php?id_no='" + id + ">");

I’m trying to concatenate the <img> tag with a variable id but I can’t seem to get the quotes right. Stupid mistake, I know, but it’s just eluding me. Can I get a little help?

Answer by Matthew Blancarte

Looks like you were misplacing an apostrophe.

jQuery("#image-div").html("<img src='get.php?id_no=" + id + "'>");

Answer by Starx

You have an misplaced single quote in your code.

jQuery("#image-div").html("<img src='get.php?id_no='" + id + ">");
                                                // ^ This one here

It should be

jQuery("#image-div").html("<img src='get.php?id_no=" + id + "'>");
                                                          // ^ Should be here
Read more

How can I get the child properties without the parent properties?

Question by user1020317

I’ve something like the following:

class a {

    private $firstVar;  

    function foo(){

        print_r( get_class_vars( 'b' ) );   
    }
}


class b extends a{

    public $secondVar;  

}

a::foo();
print_r( get_class_vars( 'b' ) );

The output is

Array ( [secondVar] => [firstVar] => ) 
Array ( [secondVar] => )

I pressume this is because when get_class_vars(‘b’) is called within a it has access to firstVar, but how can I get the function foo() to output just the class ‘b’ variables, without the parent variables?

Theres a solution on http://php.net/manual/en/function.get-class-vars.php which involves getting the a variables, then getting all a and b variables and then removing the ones that are in both, leaving just the b variables. But this method seems tedious. Is there another way?


Workaround I’m currently using:

class a {

    private $firstVar;  

    function foo(){

        $childVariables = array();

        $parentVariables = array_keys( get_class_vars( 'a' ));

        //array of 'a' and 'b' vars
        $allVariables = array_keys( get_class_vars( get_class( $this ) ) );

        //compare the two
        foreach( $allVariables as  $index => $variable ){

            if( !(in_array($variable, $parentVariables))){

                //Adding as keys so as to match syntax of get_class_vars()
                $childVariables[$variable] = "";
            }
        }

        print_r( $childVariables );
    }
}


class b extends a{

    public $secondVar;  

}

$b = new b;
$b->foo();

Answer by Starx

You must be running on lower PHP version. It works fine on codepad on your same code.

Demo: http://codepad.org/C1NjCvfa

However, I will provide you with an alternative. Use Reflection Clases:

public function foo()
{
  $refclass = new ReflectionClass(new b());
  foreach ($refclass->getProperties() as $property)
  {
    echo $property->name;
    //Access the property of B like this
  }
}

Preview

Read more

twitter bootstrap background images for two sections

Question by Looneyviticus

I am using Twitter bootstrap and I have a one page website with a top section and a bottom section. I would like to place different background images in each section; however, I cannot seem to get it to work- are there any suggestions?

Here is my HTML:

<section class="container-fluid">
<div class="row-fluid">
    <div class="span4 offset4">
    <br />
        <img src="images/logo.png" width="400" height="400" image alt="image" />
    </div>
</div>
<div class="row12">
    <h3><p class="text-center"></p></h3>
    <h4><p class="text-center"></p></h4>
    <h4><p class="text-center"></p></h4>
    <br />
    <br />
</div>
<div class="row-fluid">
<ul class="thumbnails">
    <li class="span1 offset4">
        <a href="#" class="thumbnail">
            <img src="images/MAIL_icon.png" width="50" height="50" image alt="image" />
        </a>
    </li>
    <li class="span1">
        <a href="#" class="thumbnail">
            <img src="images/DRIBBBLE_icon.png" width="50" height="50" image alt="image" />
        </a>
     </li>
     <li class="span1">
        <a href="#" class="thumbnail">
            <img src="images/TWITTER_icon.png" width="50" height="50" image alt="image" />
        </a>
     </li>
     <li class="span1">
        <a href="#" class="thumbnail">
            <img src="images/INSTAGRAM_icon.png" width="50" height="50" image alt="image" />
            </a>
         </li>
    </ul>
</div>
</section>

and my CSS:

#top_section {background-image: url(images/urban_lights.png);

}

Answer by Starx

Assign different background to your different section.

#topSection {
   background-image: url("url/to/image.jpg");
}
#bottomSection {
   background-image: url("url/to/image.jpg");
}
Read more

how to add random number to an array

Question by Lish

This is classwork. I’ve been reading and searching and everything is telling me to use the java.util.Random of which I understand how that works and wish I could use it. but my assignment specifically tells me to use the (int) (Math.random * number) of which I am having difficulty seeing where to apply into my array. everything I’ve seen has been the Random pulled from java.
It is the generate 100 random integers 0-9 and how many times they occur. If someone can assist?
My error is – Exception in “main” java.lang.array index out of bounds exemption:10 and obviously there is something in my code wrong too.

public class NumberOfTimes{

  public static void main(String[] args){

    int rand = (int)(Math.random() * 10);
    int[] counts = new int [10];

    for(int i = 0; i < 100; i++){

      counts[i]++;
    }//end for

    System.out.println("numbert" + "occurence ");

    for (int num = 0; num < counts.length; num++){

      System.out.println(num + "t" + counts[num]);
    }//end for

  }//end main

}//end NumberOfTimes   

Answer by Evgeniy Dorofeev

make this change

int[] counts = new int[100];
for (int i = 0; i < 100; i++) {
    counts[i] = (int) (Math.random() * 10);
}// end for

Answer by Starx

Your array can only hold 10 items, and on your loop you are accessing more than 10. Can be solved in two ways.

  • Either Increase your array length

    int[] counts = new int [100];
    
  • Or either decrease your count in for loop.

    for(int i = 0; i < 10; i++){
    
Read more
March 2, 2013

how to associate column record with table header?

Question by ceyrslan

I have a mysql table, one of its columns called parking space has a number in it. However, for some records the ‘parking space’-column is empty. Now, I want to call just this column in a page table where the column heads are numbered from 1 – 200 (first column: 1; second column: 2;….) So, if there is the value ’12’ in the ‘parking space’-column, then this shall show up in column ’12’ and so on, and if there is no entry for a number then the column in the page table shall be left empty. How can I associate the numbers in ‘parking space’ with that page table?

...
<?php           
$pagetable=array('1','2','3','4','5','6');//...until 200
foreach($pagetable as $value){
?>
<table border="1px" cellspacing="1" cellpadding="1">
 <tr>
  <th>
   <?php echo $value ?>
  </th>
 </tr>
<?php           
}
include("dbinfo.inc.php");
include_once("config.php");

$result = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
$results = mysql_num_rows($result);
 if ($results > 0){
    $num=mysql_numrows($result);
    $i=0;
  while ($i < $num) {
   $id=mysql_result($result,$i,"id");
   $park=mysql_result($result,$i,"park");

 ?>
  <tr>
   <td style="background-color:;">
 <?php echo $park; ?>
     <br>
 <?php if($park!=''){  ?>
 <a href="single.php?&id=<?php echo $id; ?>"><?php echo $id; ?></a>
<?php
 } 
?>
   </td>
  </tr>
<?php 
 $i++;
}
} 
?>

Answer by Starx

There are two ways, you can do this.

  1. Create all 200 rows on the database table and query it. This will omit almost all of the headache to get what you want.

  2. Do a for loop from 1 to 200 and compare the active item if it exists on the mysql results. For this you require an continuous numeric entry in the database to identify each columns individually.

    What I mean is? Column 1 in the should have corresponding record indicating 1 somewhere in its record.

    Here is an example of this:

    $result = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
    $results = mysql_num_rows($result);
    if ($results > 0) {
        $num=mysql_numrows($result);
        $rows = array();
        while($row = mysql_fetch_row($result)) {
            $rows[$row['id']] = $row;
       });
       //Now process it
    }
    
Read more
...

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