...

Hi! I’m Starx

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

Override if condition fulfills in sleep() function in php

MR.Test’s Question:

Is it possible to write sleep function with condition in php?
Example…

Public function sleepy() {
sleep(100);
If(condition a) { 
Sleep(50);
} else {
 Echo 'some thing'
 }
}

So that the sleep(50) must be override the 100 if condition full fill?

How could I achieve similar concept, in proper programming practice?

By the way, I am typing from my iphone, sorry for any unclear code, if any…

If that is only thing you are trying to do, then just move the the sleep(100) inside the else portion.

public function sleepy() {

    if(condition a) { 
        sleep(50);
    } else {
        sleep(100);
        echo 'some thing'
    }
}

If you are really trying to override the parameter like that, you can design you own function to execute the sleep afterward instead.

Read more
August 29, 2013

What does 'x' mean as the last letter in `src` attribute

MyTitle’s Question:

In some projects I noticed that javascripts included into HTML like this:

<script type="text/javascript" src="./js/score.js?x"></script>

What’s mean last ‘x’ symbol?

It is not a symbol. It is a piece of query string like on web scripts it would be something like test.php?reload=true

Such techniques might be helpful to overcome the caching problem as mentioned by SLaks on the comments.

Read more

Execute query that normally runs on a single ID for every ID

Damien.Bell’s Question:

So I have this query:

SELECT     ABS(TIMESTAMPDIFF(MINUTE, NOW(), 
(SELECT    MAX(`Time`) 
FROM       ddHistorical 
WHERE      ID = '5')))

I want to run that on every ID in my database, how would I do that?

Just remove the WHERE part, it will run on every rows.

SELECT ABS(TIMESTAMPDIFF(MINUTE, NOW(), (SELECT MAX(`Time`) FROM ddHistorical
Read more

Verifying Email address

Liondancer’s Question:

I’m trying to create a form that verifies that an email address has been entered. Not necessarily check its validity but basically sakjfsfksldjf@email.com. I was wondering how to go about doing it in PURE JavaScript and no RegEx.

    <!DOCTYPE html>

    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>Test File</title>
    </head>
        <script>
            function submitForms() {
                email_format = document.getElementById('email_input')       // want to return T or F
                if (email_format) {
                    //print email successful
                }
                else {
                   //print error message
                }         
        </script>

    <body>

        <form>
            Email:            
            <input type ="email" id ="email_input" />
        </form>

        <button type = "button" onclick = "submitForms;"> Submit All!
        </button>
    </body>
    </html>

Here is a previously answered regular expression answer. Its pretty good.

function validateEmail(email) { 
    var re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(
".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA
-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 

Credits: http://stackoverflow.com/a/46181/295264

However, the only good to verify an email address is by sending a confirmation email and hearing back.

Read more

How to change content of website loaded in iframe?

Ivan.daragan’s Question:

I need to change content of website using jQuery loaded in iframe from other domain such this:

<html>
  <head>
  </head>
  <body>
    <iframe src="site.com/somepage.html></iframe>
    <script>
      $('iframe').find('div#message').value('hello');
    </script>
  </body>
</html>

Also I added target link to whitelist.
Could any helps? Thanks.

Your script is running during runtime so it will not find the DOM of the iframe and will break. What you can do is create a function on your parent page like:

//On Your Parent page
function modifyIframeContent() {
     $('iframe').find('div#message').value('hello');
}

Then call this function from the iframe after it loads.

// On Your Iframe page
window.onload = function() {
    parent.modifyIframeContent();
}

Of course: Your iframe must be of same domain for this work.

Read more
August 26, 2013

How to check date range more than 6 months in php?

Oscar’s Question:

What I want to do is check the date range cannot more than 6 months, else will return false

here is my sample code

<?php
$date_string1 = "2013-01-01";
$date_string2 = "2013-08-01";
$date1 = date('Y-m-d',strtotime($date_string1));
$date2 = date('Y-m-d',strtotime($date_string2));

if ($date1 and $date2 range more than 6 months, so will){
   return false;
}else{
   return true;
}
?>

here is my GUI

enter image description here

Any idea how to solve my problem? thanks

$date1 = DateTime::createFromFormat('Y-m-d', "2013-01-01");
$date2 = DateTime::createFromFormat('Y-m-d', "2013-08-01");
$interval = $date1->diff($date2);
$diff = $interval->format('%m');

if($diff > 6){
 echo 'false';
}else{
 echo 'true';
}

You can use DateTime class and calculate interval based on months:

$begin = new DateTime( '2013-01-01' );
$end = new DateTime( '2013-08-01' );
$interval = $begin -> diff($end);
if($interval -> m < 6) { 
     return false;
} else {
    return true;
}

A simple airthmatic way is this

if ((strtotime('2013-01-01')-strtotime('2013-08-01')) < 5184000){
   return false;
}else{
   return true;
}
Read more

Can we add class attribute in option element?

Ifan Iqbal’s Question:

I want to add class for my option element. Is that valid to add class attribute in HTML option element?

Yes it is valid.

From the W3Schools website:

The <option> tag also supports the Global Attributes in HTML.

From which the class attribute is a part of. Please note that often, the option tag has formatting issues regarding the browser you are using, so styling it can be a little tricky.

Yes class belongs to global attributes. Any element can have it.

Source: http://www.w3.org/wiki/HTML/Attributes/_Global

Read more

version update script for a script

Marlboroman213’s Question:

I’m going to try making this easy to understand and hope it makes sense.

I have a PHP script / template and I want the end user to be able to know when I updated something, (eg. template change or a bugfix) and they can click a link to download the updated version from a remote host. I tried the scripts posted on
PHP – How to check a script version and I sorta got this script working:

<?php define('REMOTE_VERSION', http://mysite.com/_client/client_name/update/version_check.txt');
    define('VERSION', '2.0.1');
    $script = file_get_contents(REMOTE_VERSION);
    $version = VERSION;
    if($version == $script) {
        echo "<div class=success> 
    <p>You have the latest version!</p> 
    </div>";
    } else {
        echo "<div class=error> 
    <p>There is a update available!</p> 
    </div>";
    }?>

Well sort of… The .txt file on my remote server just has 2.0.1. Since they are the same version (both 2.0.1), it should read “You have the latest version!” In this case it says “There is a update available!” no matter what number I put in.

define('VERSION', '2.0.1'); //in php above 

2.0.5 //in .txt file on remote server

Says same things as it should because on the remote server is showing a new update (eg. 2.0.5). Can anyone tell me what I am doing wrong?

This might be a typo, but there is an error at your constant definition.

define('REMOTE_VERSION', http://mysite.com/_client/client_name/update/version_check.txt');
                     // ^ Missing quote
Read more
August 25, 2013

MYSQL IN Clause error

NewPHP’s Question:

I have used the below code in mysql query:

$all_PIDs=array();
foreach($pID as $p)
{
    $all_PIDs[]=$p->ID;
}
$AIDS=implode(',',$all_PIDs);
$table_tsk  = new Timesheets_Table_Tasks();
$select_tsk = $table_tsk->select()
            ->from($table_tsk, array
              (
                'Total'=>'SUM(timesheets_tasks.Time)',
                'Charged'=>'SUM(timesheets_tasks.Time_Charged)'
              ))
           ->where('timesheets_tasks.ProjectID IN ('.$AIDS.')')
            ;

But using the above code I am getting the following error:

“An error has occured
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘))’ at line 1”

I have added a quotation mark(") for IN clause. But the problem is the query only displays for the first $AIDS number. Could someone help me to clear the error?
Thanks!

It should be specified as:

->where('timesheets_tasks.ProjectID IN (?)', $all_PIDs)

so you’re passing an array of integers, not the comma-separated list of it

On your codes the quotes are not part of your MySQL query but only your PHP portion. DO this

$AIDS= "'".implode("','",$all_PIDs)."'";

And then

>where('timesheets_tasks.ProjectID IN ('.$AIDS.')'
Read more

A disabled but readable input

Fabián’s Question:

So I have two forms, one is for creating and the other for editing. Both using method="post".

There’s one difference between both, which is the code_product, that is generated via php’s rand() function, used only when creating a product (so there’s no code_product input here).

And when editing it, the code_product value is shown inside of an additional input at the top of the entire form.

Objective: code_product‘s input mustn’t be edited.

Problem: Using the disabled attribute makes it unreadable for php too.

Avoiding the asp.net (mentioned in another post), is there another way to make it uneditable, through css or javascript?

Add an attribute called readonly to your input elements. This way it cant be edited but still viewed as normal.

<input type="text" readonly />

For older browsers, you will need

<input type="text" readonly="readonly" />
Read more
...

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