...

Hi! I’m Starx

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

Count all matched fields in mysql query

Question by Ievgenii Fedorenko

My question is next: I have a mysql query like this:

SELECT student_id, name, email 
FROM student 
WHERE student_id IN ('1', '2', '3') 
    OR name LIKE '%Nick%' 
    OR email LIKE '%gmail.com%'

How can I get the number of matched fields in a in the form of a column that mysql returns
Something like this:

   ID NAME  EMAIL           MATCHED  
1. 1  Nick  nick@gmail.com  3  
2. 5  Nick  nick@yahoo.com  1  
3. 2  David david@gmail.com 2  

Thank you!!

Answer by Starx

This should work

SELECT student_id, name, email, 
     (
        CASE WHEN student_id IN ('1', '2', '3') THEN 1 END +
        CASE WHEN name LIKE '%Nick%' THEN 1 END +
        CASE WHEN email LIKE '%gmail.com%' THEN 1 END
     ) as matched
FROM student 
WHERE student_id IN ('1', '2', '3') 
    OR name LIKE '%Nick%' 
    OR email LIKE '%gmail.com%'
Read more

document.onkeypress not working

Question by Saturnix

Is there any reason the following code should not return anything in my console log?!

document.onkeypress =  zx();


function zx(){
console.log(event.keyCode);
} // zx

window.onkeypress also doesn’t work.

Other attempts has been made, like these:

document.onkeypress =  zx(event);


function zx(event){
console.log(event.keyCode);
} // zx

    document.onkeypress =  zx;


    function zx(){
    console.log(event.keyCode);
    } // zx

Thanks!

Answer by Starx

Omit the parenthesis on the call, you do not need to specify them.

Solution:

document.onkeypress =  zx;
function zx(e){
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode
    console.log(charCode);
}

Demo

Read more

CSS block positioning at end of paragraph

Question by Dibbeke

I am trying to transcribe some of Prof. Dr. Edsger Dijkstra’s EWD’s, but running into a little problem. In his writing he likes to place comments such as ‘End of Proof’ at the end of the paragraph, right aligned when there is room, or on the next line otherwise. I would like to recreate this formatting, but seem unable to do so. I’d really prefer a solution using only CSS, but if that proves impossible, JavaScript is also allowed.

Please see http://www.cs.utexas.edu/users/EWD/ewd10xx/EWD1001.PDF on page number 0 (2nd page of PDF) the comment “End of Legenda” and page number 3 (5th page of PDF) the comment “End of Remark”.

I’ve tried using the display: block / float: right combo which @starx answered with. However, as it is a float, it does not move the rest of the text down. Looking through the source document, the formatting seems ad-hoc, but it seems Dijkstra liked to keep it on the same line if possible, or move it to the next, right aligned, if not.

Searched through the different CSS specs, but I can’t as yet fathom a way to accomplish this.

Answer by JoeJ

My suggestion would be to use the :after pseudo-element to add the caption at the end of the appropriate paragraph:

.remark:after {
    content: 'End of Remark';
    color: red;
    display: inline-block;
    float: right;
}

Example: http://dabblet.com/gist/2406457

Answer by Starx

Assuming, you are giving class block to the element.

.block {
    display: block;
    width: 200px; /* minimum needed to be inline */
    float: right; 
}
Read more

How to make text appear on top of the image when hovering?

Question by qwr qwr

When a mouse hovering over the image, the image will be blurred and there will be text showing up on top of the image. I tried it myself using the code below but it appeared that the “text” move outside the image when hovering
…can anyone tell me why?

Code:

Html:

<span class ="row_1">
<a href="#">
<div class = "caption"> testing </div>
<img class = "img_link" src="image/food/food1.jpg" />
</a>
</span>

CSS:

.caption
{
display: none;
}

Jquery:

    $('a').hover(
    function(){
    var image = $(this).find('img'),
     caption = $(this).find('div');
     caption.width(image.width());
     caption.height(image.height());
     caption.fadeIn();
    },
    function(){
     var image= $(this).find('img'),
        caption = $(this).find('div');

    caption.width(image.width());
    caption.height(image.height());
    caption.fadeOut();
});

Answer by David Thomas

First off, I had to correct your HTML. A div (block-level element) is not a valid child of either a span or a elements (both of which are in-line elements). So, amended your HTML to the following:

<span class="row_1">
    <a href="#">
        <span class="caption">testing</span>
        <img class="img_link" src="http://davidrhysthomas.co.uk/img/dexter.png" />
    </a>
</span>​

That said, I’d suggest, if possible, using plain CSS for this:

a {
    display: inline-block;
    position: relative;
}
.caption {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    background-color: #333; /* for browsers that don't understand rgba() notation */
    background-color: rgba(0,0,0,0.6);
    color: #f90;
    font-weight: bold;
    line-height: 1.1em;
}
a:hover .caption {
    display: block;
}​

JS Fiddle demo.

You can, with CSS3 transitions, even implement the fade-in transition as well (which gracefully degrades for those browsers that don’t understand/implement transitions, albeit in this example you might have to use a Microsoft proprietary filter for older-IE compliance):

a {
    display: inline-block;
    position: relative;
}
.caption {
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    background-color: #333; /* for browsers that don't understand rgba() notation */
    background-color: rgba(0,0,0,0.6);
    color: #f90;
    font-weight: bold;
    line-height: 1.1em;
    -webkit-transition: all 1s linear;
    -o-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -moz-transition: all 1s linear;
    transition: all 1s linear;
}
a:hover .caption {
    opacity: 1;
    -webkit-transition: all 1s linear;
    -o-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -moz-transition: all 1s linear;
    transition: all 1s linear;
}​

JS Fiddle demo.

If you must use jQuery then I’d suggest keeping it very, very simple:

​$('.row_1 a').hover(
    function(){
        $(this).find('.caption').fadeIn(1000);
    },
    function(){
        $(this).find('.caption').fadeOut(1000);
    });​​​​​​​​

JS Fiddle demo.

References:

Answer by Starx

You dont need Javascript for this. This snippet below is enough to bring up the caption.

a:hover .caption { display: block; }

But the caption has to be positioned correctly first.

Demo

Read more

php function arguments

Question by Clint Chaney

I don’t know how or where I got this idea in my head but for some reason I thought this was possible. Obviously after testing it doesn’t work, but is there a way to make it work? I want to set $value2 without having to enter anything at all for $value1.

function test($value1 = 1, $value2 = 2) {

echo 'Value 1: '.$value1.'<br />';
echo 'Value 2: '.$value2.'<br />';

}

test($value2 = 3);

// output
Value 1: 3
Value 2: 2

Answer by rami

What you’re trying to do is called “keyword arguments” or “named arguments” and is not available in PHP in contrast to other scripting languages like Python.

If you have functions with hundreds of parameters and really want to achieve a more flexible solution than what PHP comes with, you could build your own workaround with arrays or objects, maybe in conjunction with func_get_args(). But this obviously isn’t as beautiful as real keyword arguments.

Answer by Starx

Its not entirely possible the way you want.

Simply,

function test($value1 = null, $value2 = 2) {

echo 'Value 1: '.$value1.'<br />';
echo 'Value 2: '.$value2.'<br />';

}

test(NULL, $value2 = 3);

Or, Use array as parameters

function test($array) {

if(isset($array['value1'])) echo 'Value 1: '.$array['value1'].'<br />';
if(isset($array['value2'])) echo 'Value 2: '.$array['value2'].'<br />';

}

test(array('value2' => 3));

Update:

My another attempt

function test() {
  $args = func_get_args();
  $count = count($args);
  if($count==1) { test1Arg($args[0]); }
  elseif($count == 2) { test2Arg($args[0],$args[1]); }
  else { //void; }
}

function test1Arg($arg1) {
   //Do something for only one argument
}
function test2Arg($arg1,$arg2) {
   //Do something for two args
}
Read more

PHP detect if ImageCreateFromString fail

Question by Jerome Ansia

I would like to be able to detect when i launch this function if it’s fail or not due to the memory size limit

ImageCreateFromString();

http://php.net/manual/en/function.imagecreatefromstring.php

Answer by rauchmelder

In the PHP-Manual which you’ve linked there is the solution already written:

Return Values

An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.

Answer by Starx

If you had read the manual you linked in your question, there is an answer already.

An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.

There is an example for that

$im = imagecreatefromstring($data);
if ($im !== false) {
    // OK
}
else {
    echo 'An error occurred.';
}
Read more

How do create a global visit counter that echoes an image for every visit?

Question by Nathan Bankhead

Basically I want to create a global visit counter of a web page, then I want to display an image for every visit. So if 10 people have visited the page, 10 random images from the server will be echoed on that page. When the 11th visitor arrives on the page a new random image will be echoed and so on…

So I need help with two things really –

  1. I have a very basic visit counter but it only works in sessions, I need it to work globally?
  2. How do I echo images according to the number of visits?

Here is the basic code I have for a visit counter:

if(isset($_SESSION['views']))
   $_SESSION['views']=$_SESSION['views']+1;
else
   $_SESSION['views']=1

echo "Page views: ".$_SESSION['views'];

I am still a massive beginner at php and any help would be hugely appreciated 🙂

Thanks guys.

Answer by Starx

SESSIONS are NOT for global storage.

They are only alive till the website is open.

You should use database to store the global variable.


Now, coming to the image display part. You can name of images with number specific to no of visits.

For example:

4.jpg will be the Image that is when to the fourth guy

Next, you can use a simple snippet like this

$visitCounter = "?"; //Get the count using a logic
echo "<img src="$visitCounter.jpg" />"; //Use it to create a image path
Read more

jquery div slider when postback div close

Question by saadan

I have a jquery slider that open and close my div. but when the page get a postback the div is closed.
and i want the div to stay open.

my slider

 if ($(".div").is(":hidden")) {
            $(".div").slideDown(1000); // slide it down

        } else {
            $(".div").slideUp(1000); // hide it
        }

I thought about change the address, such as

website.com#open

and then check the adress
but how can i do this ?

Answer by Starx

When the page postbacks, the markup reverts to the original state. So, $(".div").is(":hidden") will always return true.

You can create some sort of state identifier and use that to check the state.

Read more

jquery autoscroll plugin not firing

Question by preahkumpii

I am sure my issue is a result of my inexperience in jquery and javascript. I am trying to use an autoscroll jquery plugin. I just stares at me when I click the link that is supposed to activate the scroll. Can someone help? Here is what I have:
I have called the relevant scripts in the head tag.
In at the end of my body tag I have this:

<script type="text/javascript">
$(document).ready(function() {
$("a.hello").click(function () {
    $("#text").autoscroll("toggle", { 
        start: { 
            step: 50, 
            scroll: true, 
            direction: "down", 
            pauseOnHover: true 
        }, 
        delay: 5000, 
        ffrw: { 
            speed: "fast", 
            step: 100 
        } 
    });
});
});
</script>

Then, I am trying to fire the script using an anchor, like this:

<a href="#" class="hello">start/stop</a>

The id of the div that I want to ‘pause on hover’ is “text”.
The source and instructions of this plugin is found here. Thanks.

EDIT:
The function that calls some html from other files based on form selects and puts it into the <div id="text"></div>.

function clickMe() {
    var book = document.getElementById("book").value;
    var chapter = document.getElementById("chapter").value;
    var myFile = "'files/" + book + chapter + ".html'";
    $('#text').load(myFile + '#source')
}

Answer by Starx

You forgot to wrap the code inside a

$(document).ready(function() {
..
});
Read more
...

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