...

Hi! I’m Starx

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

Match 2 dates in php

Question by user1307519

I need to match a date from database which is in format e.g 2012-04-12 with month e.g January using php can any one please help
It`s ok if there is any alternate answer
Pl help……..

Answer by Starx

Quite a horrible question, but I will guess the problem.

To retrieve the month from the database

$date = $row['date']; //example of retrieving data row
$month =  date("M",strtotime($date)); // retrieving the month of the date


//Now match them

if($month == "January") {
  //do something
}
Read more

Spinning Two Images BEHIND an Image

Question by Joe Isaacson

I have two images (bike wheels) that are positioned behind the bike frame image, but when I use Javascript to rotate the wheels, they appear to be in front of the bike frame image.

HTML

<div id="bike">
    <img src="frame.png">
</div>

<div id="wheel">
    <img class="spin" src="wheel.png">
    <img class="spin" id="two" src="wheel.png">
</div>      

JS

$(function() {
    var $elie = $(".spin");
    rotate(0);
    function rotate(degree) {        
        $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});  
        $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});                      
        timer = setTimeout(function() {
            rotate(++degree);
        },10);
    }
});

Answer by Starx

Give a higher z-index value to the div with bike

<div id="bike" style="z-index: 2">
    <img src="frame.png">
</div>

<div id="wheel" style="z-index: 1;">    
    <img class="spin" src="wheel.png">
    <img class="spin" id="two" src="wheel.png">
</div>  
Read more

How to position divs on top of one another

Question by Bobby Francis Joseph

I want to position divs on top of one another. I have created a fiddle. I have three divs. Each div contains an image. I want to position divs so that the div having the largest image is at the bottom and the one having smallest image is on top.

http://jsfiddle.net/bobbyfrancisjoseph/7spcZ/2/

http://jsfiddle.net/bobbyfrancisjoseph/7spcZ/2/show/

Answer by Muhammad Sannan

Use position absolute with z-index.

use below css

#page-left {
float: left;
margin:5px;
}

#page-right {
float: left;
margin:5px;
}

#largest {
position: absolute;
    z-index: 1;
}
#medium {
position: absolute;
    z-index: 2;
}
#smallest {
position: absolute;
    z-index: 3;
}

http://jsfiddle.net/sannankhalid/sc8qE/

Answer by Starx

You can use z-index & position: absolute to treat the elements as layers. But as per your requirement and element order, a simple position: absolute is enough

#page1 div {
    position:absolute;
}
Read more

Click in iframe register parent window

Question by Zolka

I have a webpage where I have an Iframe. When someone clicks something in the Iframe I want to detect it in the parent window.

I see there are similar threads in the forum but no one solved my issue.

Zolka

Answer by GregL

You need to use the jQuery .contents() method to retrieve the contents of the iFrame, and then search within that for your .click1 elements.

See the following jQuery code (works in v1.7 up):

$('#1_iframe').load(function() {
    $(this).contents().find('#myGrid').on('click', '.click1', function() {
        alert('Click detected!');
    });
});

EDIT: Wrapped it in a .load() event handler.

Answer by Starx

Attach a event on the iframe

$(document).click(fucntion(e) {
   var targ = e.currentTarget();

   //Now send this to the parent function
   parent.NewClick(targ);
});

Now the NewClick() function in the parent window, will know which button was clicked.

Read more

Fastest way to checked checkboxes that have a value of specific list in jQuery

Question by Saeid

This is My HTML Dom:

<input type="checkbox" class="chk-act" name="actionChk" value="17">
<input type="checkbox" class="chk-act" name="actionChk" value="18">
<input type="checkbox" class="chk-act" name="actionChk" value="19">
<input type="checkbox" class="chk-act" name="actionChk" value="20">
<input type="checkbox" class="chk-act" name="actionChk" value="21">

And I have a jQuery script that returned a JSon response by ajax:

["18","20","21"]

The list can be as long as up to 200 members. So I am interested to find out the fastest way to checked checkboxes, that have a value in above list, when the response is returned. What is your suggestion?

Answer by Jibi Abraham

The fastest way would be to add an id identifier to your list of checkboxes. For example –

<input type="checkbox" class="chk-act" name="actionChk" value="17" id='chk-act-17' />
//incidentally, I hope the lack of a closing '/' was an oversight
//when you get your JSON response, in your ajax success or done methods
var resp = ["12", "232"],
    respLength = resp.length;
for(var i = 0; i < respLength; i += 1){
    $('#chk-act-' + resp[i]).prop('checked', true);
    //if your are using jquery 1.7+ that is, otherwise use, 
    $('#chk-act-' + resp[i]).attr('checked', 'checked');
}

JS Perf Tests

Comparing the two current answers, the OP’s requirement of “fastest” would be better served by going down the uglier ‘id‘ implementation.
Js Perf

FIddle added

JS FIddle

Posting code from fiddle-

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
    checkboxes = $('.chk');

checkboxes.each(function(i, item){
    $(this).prop('checked', false);
});

arr.forEach(function(item, i) {
    $('#chk_' + item).prop('checked', true);
});

Answer by Starx

Mixing jQuery on this

arr = ["18","20","21"];
$("input:checkbox").prop('checked', false); //If you need to uncheck other boxes too
$.each(arr, function(k,v) {       
   $("input[value=""+v+""]").prop('checked', true);
});

Demo 1 | Demo 2: with all other checks removed

Read more

Background Images in HTML Email

Question by user1307242

I just want to add background image and want to write text over it. I have tried everything. Please give me full proof method for this.
Thank You

Answer by Starx

While giving an image on the email, the link should always be relative path.

Here is example email content to show what i mean

$content = '<div style="background:url('http://yourdomain.com/images/yourimage.jpg');">';
                                      //  ^ See the direct path to the image given here
$content .= "your text";
$content .= "</div>";
Read more

PHP, counting time script

Question by Jake

Is there a way to make a countdown script with PHP?

4shared.com or megaupload.com use similar script, and it starts to count from 20 seconds to 0 second.

I can clearly see how many seconds left on the web page until I can click download page.

Is this jquery?

Answer by landons

This is with a simple javascript timer. It’s just as easy with native javascript as it is with jQuery (or any other library):

<script type="text/javascript">
var seconds_left = 20;
var interval = setInterval(function() {
    document.getElementById('timer_div').innerHTML = --seconds_left;
    if (seconds_left == 0)
    {
        clearInterval(interval);
        alert('do something here!');
    }
}, 1000);
</script>

Answer by Starx

You need to mix up PHP & Javascript for this

First PHP

Send headers, so that page will navigate to the download page .

header( "refresh:30;url=download.php" );
echo 'The download will begin in 30 secs. If not, click <a href="download.php">here</a>.';

Then Javascript

This handles the part where we show time to the user, so that he know.

var count=30; //30 seconds
var counter = setInterval(timer(),1000); //1000 will  run it every 1 second
function timer()
{
  count=count-1;
  if (count <= 0)
  {
     clearInterval(counter);
     return;
  }

  document.getElementById("placetoshowtime").innerHTML = count; //display the time to user
}

Small demo of JS Part.

When, the java script finishes ticking, the PHP will already have redirected to download page. So it creates the illusion you are after.

Read more

Show multiple rows in MySQL

Question by ramesh

I had a table like this

id   |   name 
------------------
1    |   SAM1
2    |   SAM2
1    |   SAM1
3    |   SAM3
7    |   SAM7
6    |   SAM6

I need to show the results using this query

SELECT name,id FROM tblnameWHERE id IN (1,2,7,6,1)

and getting the following result

id   |   name 
------------------
1    |   SAM1
2    |   SAM2
7    |   SAM7
6    |   SAM6

My problem is this skipped last id , ie 1 . I need something like this

id   |   name 
------------------
1    |   SAM1
2    |   SAM2
7    |   SAM7
6    |   SAM6
1    |   SAM1

With out using the loop query ( like follows ) any other method for doing this ?

$ids=array(1,2,7,6,1);
$i=0;
foreach($ids as $id){

$sql=mysql_query("SELECT * FROM tblname WHERE id=$id");
// Store value to array 

}

Please help

Answer by ShinTakezou

The query

SELECT name,id FROM tblname WHERE id IN (1,2,7,6);

should show duplicate rows; e.g. if there are really in the table two distinct rows with the very same id, then the query will show them (since there’s no DISTINCT keyword).

Instead, if you want to create duplicate lines starting from a table containing single lines, you have to join your table with a table having repeated 1 (in your case); another way could be to use union like this:

SELECT  name, id FROM tblname WHERE id IN (1,2,7,6)
  UNION ALL
SELECT name, id FROM tblname WHERE id = 1;

Edit

Since your id is a primary key, it will be unique, hence the “problem” you’re experiencing. If you want to allow duplicate rows on insert, remove the primary key. If you need it, consider the possible solutions suggested above.

Answer by Starx

What you are attempting is wrong.

Both the fields have same id and same value as well. You said id is your primary key on your table.

A primary key cannot be duplicated among the rows. That is the whole point of having a primary key

You mustn’t have declared the id field as primary key.

  • Remove the bottom row
  • Add primary key to the field , run this query

    ALTER TABLE `tablename` ADD PRIMARY KEY(id) AUTO_INCREMENT
    

Now from this point ahead, you will have unique id for all the records you have and you will have no problem on selecting the rows.

Read more
April 1, 2012

SQL syntax error while using MySQL and PHP

Question by liamwli

I am trying to make a thing, but I have hit a problem. I have tried all I know, but I am new to MySQL, so I have hit a dead end.

This code:

<?php
    require('cfg.php');
    mysql_connect($server, $user, $pass) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    if (isset($_GET['name'])){
        $name = $_GET['name'];
    }
    else
        if (isset($_POST['submit'])){
            $name = $_POST['name'];
            $name1 = $_POST['name1'];
            $name2 = $_POST['name2'];
            $name3 = $_POST['name3'];
            mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 ) ") or die(mysql_error());
            echo ("Data entered successfully!");
        }
?>

<html>
    <head>
        <title>Random giffgaff simmer</title>
    </head>
    <body>
        <form action="" method="post">
            <p>Your Username: <input type="text" name="name"></p>
            <p>Username 1: <input type="text" name="name1"></p>
            <p>Username 2: <input type="text" name="name2"></p>
            <p>Username 3: <input type="text" name="name3"></p>
            <p>Username 4: <input type="text" name="name4"></p>
            <p>Username 5: <input type="text" name="name5"></p>
            <p>Username 6: <input type="text" name="name6"></p>
            <p><input type="submit" name="submit" value="Submit"></p>
        </form>
    </body>
</html>

Brings this error:

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

Now, that would tell me that this SQL code has a syntax error:

INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 )

But I don’t think I can see one?

Answer by Starx

You haven’t quoted your query. You should quote every field like this

INSERT INTO data (name, name1, name2, name3) VALUES('$name', '$name1', '$name2', '$name3' )

As an tribute to TheCommonSense, I am providing a mysqli version using correct prepared statement for data safety

$db = new mysqli(...);
$stmt = $db -> prepare("INSERT INTO data (name, name1, name2, name3) VALUES(?, ?, ?, ?)");
$stmt -> bind_param("ssss", $name, $name1, $name2, $name3);
$stmt -> execute();
$db -> close()
Read more

PHP if date equals then

Question by huddds

Hi I’m trying use a datepicker on a field I have. I’m trying to set the date field up so the user can only edit this field if the date value in the database is set to deafault (0000-00-00). If there is a value that’s not equal to default I want to show the date created.

Here’s the code I have attempted:

          if( $post['Date'] = var_dump(checkdate(00, 00, 0000))){ 
          echo "<input type="text" class="datepicker" name="pDate" style="border:#000099; margin:10px;" value="";
          echo $post['Date'];
          echo ""> <input id="start_dt" class="datepicker">";
          }
          if( $post['Date'] != var_dump(checkdate(00, 00, 0000))){ 
          echo "<span>date created: </span>";
          echo $post['Date'];

          }

It’s not working atm so any help or a point in the right direction would be great.
Please also take into account I haven’t added any proper styling so I’m only after help with the functionality.

Many thanks.

Answer by Starx

var_dump() is used for debugging purpose rather than inside conditional expression. Next, using = assigns the values not checks for them. You are assigning the values of var_dump() results to $post['Date'] So change them to ==

You should be trying to to something like this

  if( $post['Date'] == checkdate(00, 00, 0000)){ 
      echo "<input type="text" class="datepicker" name="pDate" style="border:#000099; margin:10px;" value="".$post['Date']"">";
      echo "<input id="start_dt" class="datepicker">";
  } else {
      echo "<span>date created: </span>";
      echo $post['Date'];
  }
Read more
...

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