...

Hi! I’m Starx

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

Replacing comma with & before the last word in string

AlexB’s Question:

Having little trouble with what should ideally be a simple thing to accomplish.

What I am trying to do is to replace ', ' before the last word with &.

So basically if word in $ddd exist than need it as & DDD and if $ddd is empty than & CCC

Theoretically speaking, what i do need to acive is the following:

“AAA, BBB, CCC & DDD” when all 4 words are not empty
“AAA, BBB & CCC” when 3 are not empty and last one is
“AAA & BBB” when 2 are not empty and 2 last words are empty
“AAA” when only one is returned non empty.

Here is my script

    $aaa = "AAA";
    $bbb = ", BBB";
    $ccc = ", CCC";
    $ddd = ", DDD";
    $line_for = $aaa.$bbb.$ccc.$ddd;
$wordarray = explode(', ', $line_for);
if (count($wordarray) > 1 ) {
  $wordarray[count($wordarray)-1] = '& '.($wordarray[count($wordarray)-1]);
  $line_for = implode(', ', $wordarray); 
}

Please do not judge me, since this is just an attempt to create something that I have tried to describe above.

Please help

I think this is the best way to do it:

function replace_last($haystack, $needle, $with) {
    $pos = strrpos($haystack, $needle);
    if($pos !== FALSE)
    {
        $haystack = substr_replace($haystack, $with, $pos, strlen($needle));
    }
    return $haystack;
}

and now you can use it like that:

$string = "AAA, BBB, CCC, DDD, EEE";
$replaced = replace_last($string, ', ', ' & ');
echo $replaced.'<br>';

Here is another way:

$str = "A, B, C, D, E";
$pos = strrpos($str, ","); //Calculate the last position of the ","

if($pos) $str = substr_replace ( $str , " & " , $pos , 1); //Replace it with "&"
// ^ This will check if the word is only of one word.

For those who like to copy function, here is one 🙂

function replace_last($haystack, $needle, $with) {
    $pos = strrpos($haystack, $needle);
    return $pos !== false ? substr_replace($haystack, $with, $pos, strlen($needle)) : $haystack;
}
Read more
July 26, 2013

on blur of input field validate field and cancel blur event if not valid

Xavier DSouza’s Question:

I am validating a field on blur event. And if the field is invalid I want the focus to remain in same field and not go to next field. When I do $(this).focus() within my blur function it only works in Chrome and not in Firefox. I tried the settimeout function but the problem is that the focus goes to next field(#myInput2) and then comes back to field(#myInput1). I dont want that as the next field also raises error cause it will be blurred again and it is empty. Is there a way to solve this in Firefox??
My code :

$('#myInput1').blur(function () {
    if (!validField1($(this).val())) {
        alert("Invalid");
        $(this).focus(); // Does not work in FF 
    }
});


$('#myInput2').blur(function () {
    if (!validField2($(this).val())) {
        alert("Invalid");
        $(this).focus();
    }
});

I asked this question once, these are generally browser features which is not lock down a user to one input box. User should have choice of going away if they wanted, whether or not it is valid.

So, Focus the same element after the blur event is disallowed.

Read more

Is there a reason my html isn't rendering?

User2617514’s Question:

I’m completely stuck. All of my html documents are validated and properly referenced to each other, but when I load the primary html, it doesn’t render.

My objective is to have a page with two sides: The left side which displays a default image and caption, and the right side which includes a button to load a different random image of five and caption on the left side via different html documents.

I’m making different sides with “iframes.”

Also how do change the width of the iframes?

<!DOCTYPE html>

<html>
    <head>
        <title>Free Jokes!</title>
        <meta charset="utf-8">
        <meta name="author" content="Justin Partovi, CS80 1184, Summer 2013">
        <link href="final%20project.css" rel="stylesheet">
    </head> 

    <body>
        <h1 id="shadow">Welcome to Free Jokes!</h1>
        <iframe id="left" src="left.html"></iframe>
        <iframe id="right" src="right.html"></iframe>
    </body>
</html>

The left side:

(Please let me know if there is a better way to accomplish my objective other than the way I am doing now)

<!DOCTYPE html>

<html>
    <head>
        <title>Your Joke!</title>
        <meta charset="utf-8">
        <script>
        var randomnumber

        function clickForJoke() {
        randomnumber=math.floor( 1 + Math.random() * 15);

        switch ( randomnumber ) {
        case 1:
            window.open( "joke1.html", target="right" );
            break;
        case 2:
            window.open( "joke2.html", target="right" );
            break;
        case 3:
            window.open( "joke3.html", target="right" );
            break;
        case 4:
            window.open( "joke4.html", target="right" );
            break;
        case 5:
            window.open( "joke5.html", target="right" );
            break;

        default:
            window.open( "joke.html", target="right" );
    </script>
</head>
</html>

The right side:

(Did I make the button incorrectly?)

<!DOCTYPE html>

<html>
    <head>
        <title>Final project</title>
        <meta charset="utf-8">
        <link href="final%20project.css" rel="stylesheet">
    </head>

    <body>
        <button type="button" id="jokeButton" name="jokeButton" onclick="clickForJoke">Click for your joking pleasure!</button>
    </body>
</html>

The default image and cation:

<html>
    <head>
        <title>Default joke</title>
        <meta charset="utf-8">
        <link href="final%20project.css" rel="stylesheet">
    </head>

    <body>
        <p><img alt src = "laughing%20gif.gif"></p>
        <p><b>Click the button to the right to get a free joke!</b></p>
    </body>
</html>

I didn’t make the five other html documents yet.

You cannot just control a different iframe from another iframe. You have to invoke it from the parent.

<button type="button" id="jokeButton" name="jokeButton" onclick="parent.iframes['left'].clickForJoke();">Click for your joking pleasure!</button>

Suggestion:

The purpose you are doing right now does not require you to use two iframe. It can be on the same utilizing AJAX. If you like I can show you a simple way to do this using jQuery.

Read more
July 25, 2013

Cannot extract information like user's email address from facebook connect

Starx’s Question:

I am trying to use simple Facebook Connect to login users on a website. I am using most basic form of the code to do this:

FB.getLoginStatus(function(response) {
  if (response.status == 'connected') {
    getCurrentUserInfo(response)
  } else {
    FB.login(function(response) {
      if (response.authResponse){
        getCurrentUserInfo(response)
      } else {
        console.log('Auth cancelled.')
      }
    }, { scope: 'email' });

  }
});

function getCurrentUserInfo() {
  FB.api('/me', function(userInfo) {
    console.log(userInfo);
  });
};

I get the basic information only but I do not get any email. I have also set the permission settings on the application too.

Application permission Settings

I test the code using my facebook account. I can connect successfully but I cannot see my email address and my settings for my email is also public.

Can I get some help with this?

Ok, Just figured this out. The problem was that the scope was somehow not being passed to the login function.

All I had to do was modify the fbml code for the login button with the scope and it was asking for the email address authorisation.

<fb:login-button show-faces="true" width="200" max-rows="1" scope="email"></fb:login-button>
Read more

mysql_query() keeps failing

Dylan’s Question:

So I have a MySQL database that I’m trying to query, and the query keeps failing. I know this because immediately after my query I call mysql_fetch_array() to parse the result of the query into something usable. At this point, however, my script pukes, saying that mysql_fetch_array() expects a resource, but a boolean was given. The only way this could have happened is that mysql_query() failed and returned false instead of a resource. My relevant files are here.

The first file contains my MySQL configuration.
The second file contains the include file that contains the function with the problem.
The third file contains the actual webpage that calls the function with the problem.

The fourth file is completely unrelated, but since I couldn’t post each of these links individually (I don’t have enough rep points yet), I had to give you all of them at once.

Yes, mysql_fetch_array() does require a valid resource to fetch something. Before I tell you your soluction, I would like to point that MYSQL_* API is now deprecated So I will tell you using mysqli API

$query = "YOUR QUERY STATEMENT";
$result = mysqli_query($query); // Now this statement should return a mysql resource
$row = mysqli_fetch_assoc($result);
Read more

Does it make sense to clone copies of dependencies (Dependency Injection)?

Maxiscool’s Question:

Say I have a class that has a few methods that depend on another object in order to carry out their duty. The difference being they all depend on the same class of object, but need different instances of the class. Or more specifically, each method needs a clean instance of the class because the methods will be modifying the state of the dependency.

Here is a simple example I had in mind.

class Dependency {
    public $Property;
}


class Something {
    public function doSomething() {
        // Do stuff
        $dep = new Dependency();
        $dep->Property = 'blah';
    }

    public function doSomethingElse() {
       // Do different stuff
       $dep = new Dependency(); 
       $dep->Property = 'blah blah';
    }
}

Technically I could do this.

class Something {
    public function doSomething(Dependency $dep = null) {
        $dep = $dep && is_null($dep->Property) ? $dep : new Dependency();
        $dep->Property = 'blah';
    }

    public function doSomethingElse(Dependency $dep = null) {
       $dep = $dep && is_null($dep->Property) ? $dep : new Dependency();
       $dep->Property = 'blah blah';
    }
}

My trouble here is I constantly have to check that the dependent object being passed in is in the correct state. The state being newly created. So instead I was thinking of just doing something like this.

class Something {
    protected $DepObj;

    public function __construct(Dependency $dep) {
        $this->DepObj = $dep && is_null($dep->Property) ? $dep : new Dependency();
    }
    public function doSomething() {
        // Do stuff
        $dep = clone $this->DepObj;
        $dep->Property = 'blah';
    }

    public function doSomethingElse() {
       // Do different stuff
       $dep = clone $this->DepObj;
       $dep->Property = 'blah blah';
    }
}

This allows me to get one instance of an object in the correct state, and I can just copy it if I need another one. I’m just curious if this makes sense, or if I’m over looking a fundamental guideline about dependency injection and keeping code testable.

If doSomething() and doSomethingElse() both does similar things in two functions, then its a bad choice. It this case created a feeder function and feed two different object to this function.

But if there are both responsible for two different action requiring a clone of the dependency object, then it is not bad.

Read more
July 24, 2013

Jquery redirect after php login

Kingofslowmo’s Question:

The Problem

I can’t seem to get the javascript to redirect after the php has echoed “Success”.

Im basically just trying to make it where the javascript post my form data and then the usesr is redirected to their account page. I did have this being done via php, but I wanted the luxury of being able to stay on the same page while logging in.

The Javascript

 <script>
$(document).ready(function() {
//When the form with id="myform" is submitted...
$("#login_form").submit(function() {
     //Send the serialized data to formProcessor.php.
     $.post("login.php", $("#login_form").serialize(),
     //Take our repsonse, and replace whatever is in the "formResponse"
     //div with it.
    function(data) {
          if(data == "Success"){
          location.href="home";
      }
     }
);
return false;
});
});
</script>

You redirect using document.location not location.href

document.location="home.html";
Read more

How to access info stored in session array?

JL.’s Question:

Given the following code:

session_start();

$cart = $_SESSION['cart'];

print_r($_SESSION['cart']);

I can then see what I want to access:

Array ( [153c740f526f2fa8aac9e1ddfdce2716] => Array ( [deal_id] => 38 [variation_id] => [variation] => [quantity] => 6 [data] =>……

There is still more but that is the basics…

What I want to be able to do is get and set the quantity:

So I’ve tried:

$cart = $_SESSION['cart'];

for ($i = 0 ; $i < count($cart) ; $i ++)
{
    echo "The session variable you want" . $_SESSION['cart'][$i]['deal_id'];
    echo "<br>";

}

But there is no output, what am I doing wrong?

You will simplify things by using foreach loop

foreach ($_SESSION['cart'] as $k => $data) {
    echo "The session variable you want" . $data['deal_id'];
    echo "<br>";
    $_SESSION['cart'][$k] = "new Value";
}
Read more

mysql_fetch_assoc() returning single row even though there are many rows

Nanu146’s Question:

i am trying to run this program but unexpectedly the mysql_fetch_assoc() function is returning only the first entry even though there are many entries and further more in foreach loop error say that illegal ‘parameter’ username is given

<?php
$dbc=mysql_connect("localhost","root","nanu");
mysql_select_db('users');
$getQuery='SELECT * FROM userst  ORDER BY username';
$result=mysql_query($getQuery,$dbc);
$rel=mysql_fetch_assoc($result);
echo'<pre>'.print_r($rel).'<pre/>';
echo"<br/>".$rel['username']."<br/>";
foreach($rel as $Query[]){
echo $Query['username'];
}
?>

$rel=mysql_fetch_assoc($result); will only fetch one row at a time depending on the resource pointer.

This pointer will increase once you use that statement, so using it with a loop statement will give you all the rows.

while ($rel = mysql_fetch_assoc($result)) {
    echo $rel['username'];
}

Please try more safer API’s like mysqli or PDO instead of mysql_* API. They are deprecated.

http://php.net/manual/en/mysqlinfo.api.choosing.php

It is not recommended to use the old mysql extension for new development, as it has been deprecated as of PHP 5.5.0 and will be removed in the future.

Read more
...

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