...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
November 26, 2010

jQuery question regarding if statement and position moving

Question by alexcu

I’m trying to write a program where basically the user clicks on an image and the image will then move to the right by 25px. The image moves when I click on it, but I tried to add a piece of code which makes the image return to the left of the window when it passes the right side of the window. I’ve tried using an If statement in the animation’s procedure but it doesn’t seem to work. Here’s what I have:

$('#image').click(function() {
$(this).animate({
   left: '+=155',
function() {
    if ($(this).left > $(document).width)  {
 $(this).left = 0
  }
   };

    });

});


Am I using the wrong syntax or is my function wrong? Thanks for your help.

Answer by Starx

Where is your duration?

Try this,

$('#image').click(function() {
     $(this).animate(
            {
               left: '+=155'
            },
            5000,
            function() {
                if ($(this).left > $(document).width)  {
                $(this).left = 0
                }    
       );
});
Read more

How to insert chinese character in mysql table?

Question by user319198

I want to save data in Chinese language in mysql table.

Can anyone tell me what settings I have to do for it in mysql and PHP.

My table will save data in both English and Chinese some column English other Chinese . Is it possible with single table.

Any help will be appreciated.

Answer by Guixing Bai

Use UTF-8 when you create table

create table xxx ()CHARACTER SET = utf8;

Use UTF-8 when you insert to table

set names utf8; insert into xxx (xx,x);

Answer by Starx

Set the character set to UTF-8, in mysql.

Check this for reference

http://confluence.jetbrains.net/display/TCD/Configuring+UTF8+Character+Set+for+MySQL
http://dev.mysql.com/doc/refman/5.0/en/charset-mysql.html

Read more

how to pop a dialog box on button click

Question by shalu

Hello Friends
I want to upload a image but according to requirement when click on button a pop window display and inner part of pop window display browse field using code something like

<form action="index.php" method="post" onsubmit="">
    <div><label>Name:</label> <input type="text" name="form[name]" /></div>
    <div><label>File:</label> <input type="file" name="form[file]" /></div>
    <div><input type="submit" value="SUBMIT" /></div>
</form>

actually i want to show this browse field in pop-up window.
Please reply me regard this
Thanks

Answer by Starx

Just give a myform ID to your form hide it, using display:none; and try this code

<a href="#" onClick="document.getElementById('myform').style.display='';">Show Browse</a>

UPDATE

I have created a demo of what you wanted. Check it here http://jsfiddle.net/Starx/rVw9M/

Since you are unfamilier with jquery, you need jquery library for this to run put this in your head (HTML Pages’ Head :D)

<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
Read more
November 23, 2010

How could I loop through this json object in php file?

Question by XCeptable

I have converted an xml object returned from a php function into json format to send it to js file like.

function searchResults($q) { ...
    $xml = simplexml_load_string($result);
    return json_encode($xml); }

I receive/use it in js like

  var msg_top = "<"+"?php echo searchResults('windows');"+"?"+">";

Then I receive it back in php & decoded.

      $json = $_POST['msg_top'];
      $msg = json_decode($json);

Now how do I loop through it to get all values of its certain properties that I could have get from xml object(which I converted into json). This is how I loop over xml object to get all values of its certain properties:

   foreach ($xml->entry as $status) {
   echo $status->author->name.''.$status->content);
   }

How do I get all those values from decoded json object $msg?
EDITED
I tried in same HTML where I am using js to receive & POST php search function data via ajax, I tried following code to loop through json in php. But it did not show anything.

$obj = searchResults(testword);//serach function returns json encoded data
$obj = json_decode($obj, true);
$count = count($obj);  
for($i=0;$i<$count;$i++)
{
echo $obj[$i][content];}// using xml for it, I get ouput like foreach ($xml3->entry as 
                       // $status) {status->content}

Answer by Yorirou

By default, json_decode returns an stdClass. stdClass-es can be used the same way as associative arrays with foreach.

Alternatively, you can ask json_decode to return an associative array:

$array = json_decode($_POST['foo'], TRUE);

Answer by Starx

I think you have to use $msg for the FOR LOOP as it is the array.

Try to see what it hold using this

echo "<pre>".print_r($msg)."</pre";
//And if you see the correct array structure
foreach($msg as $key=>$value) {
  //do your things
}
Read more
November 21, 2010

How can I make a CSS table fit the screen width?

Question by David B

Currently the table is too wide and causes the browser to add a horizontal scroll bar.

Answer by T.J. Crowder

If the table content is too wide (as in this example), there’s nothing you can do other than alter the content to make it possible for the browser to show it in a more narrow format. Contrary to the earlier answers, setting width to 100% will have absolutely no effect if the content is too wide (as that link, and this one, demonstrate). Browsers already try to keep tables within the left and right margins if they can, and only resort to a horizontal scrollbar if they can’t.

Some ways you can alter content to make a table more narrow:

  • Reduce the number of columns (perhaps breaking one megalithic table into multiple independent tables).
  • If you’re using CSS white-space: nowrap on any of the content (or the old nowrap attribute, &nbsp;, a nobr element, etc.), see if you can live without them so the browser has the option of wrapping that content to keep the width down.
  • If you’re using really wide margins, padding, borders, etc., try reducing their size (but I’m sure you thought of that).

If the table is too wide but you don’t see a good reason for it (the content isn’t that wide, etc.), you’ll have to provide more information about how you’re styling the table, the surrounding elements, etc. Again, by default the browser will avoid the scrollbar if it can.

Answer by Starx

table { width: 100%; }

Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.

$("#tableid").width($(window).width());

If not, use this snippet

<style>
    body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
    <tr>
        <td>Just a Test
        </td>
    </tr>
</table>

You will notice that the width is perfectly covering the page.

The main thing is too nullify the margin and padding as I have shown at the body, then you are set.

Read more

PHP – Visitors Online Counter

Question by anon445699

I have the following code to count visitors on my PHP site. It works fine on my local development machine using WampServer but when I uploaded my files to my hosting account for testing I realized that it does not work properly.

I get really high number count and also noticed the session are never deleted so they just keep accumulating.

It is a simple session counter. Is there a better way of doing it? Could some one please show me or point me to some article? Thank you!

<?php
//------------------------------------------------------------
// VISITORS ONLINE COUNTER
//------------------------------------------------------------
if (!isset($_SESSION)) {
  session_start();
}
function visitorsOnline()
{
    $session_path = session_save_path();
    $visitors = 0;
    $handle = opendir($session_path);

    while(( $file = readdir($handle) ) != false)
    {
        if($file != "." && $file != "..")
        {
            if(preg_match('/^sess/', $file))
            {
                $visitors++;
            }
        }
    }

    return $visitors;
}
?>

Answer by Starx

If you want your own internal counting system then I would suggest, storing such information related to website in database. And update the record everytime a user browses the website.

Read more
November 18, 2010

Using form contents to add values to $_SESSION array

Question by BigRob

I’m trying to make a page that takes a form submission and adds the contents as a new value in the $_SESSION() array, what seems to be happening though is the value is being overridden.

The form has 3 text inputs named a, b and c and refreshes the page on submission. What tells me it’s being replaced is $_SESSION[0] will display 1 2 and 3 as defined below, then the next row defined by $_POST will be the same but with the array values replaced by the last submitted values rather than adding the last submitted as another row.

<form action="test2.php" method="post">
<input type="text" name="a">
<input type="text" name="b">
<input type="text" name="c">
<input type="submit" value="Submit">
</form>

<?php
    if (isset($_POST['a']))
    {
     $a = $_POST['a'];
     $b = $_POST['b'];
     $c = $_POST['c'];
     $order = array('a' => $a, 'b' => $b, 'c' => $c);
     $_SESSION[0] = array('a' => 1, 'b' => 2, 'c' => 3);
     $_SESSION[] = $order;
     $count = count($_SESSION);
     for ($i = 0; $i < $count; $i++) {
      echo "w: " . $_SESSION[$i]['a'] . "n";
      echo "h: " . $_SESSION[$i]['b'] . "n";
      echo "p: " . $_SESSION[$i]['c'] . "n";
      echo "<br />";
      }
    }
?>

Would be extremely grateful for any help,
Thanks

Answer by Nick Pyett

It looks to me like you are trying to add a new array to a new $_SESSION var each time the form is submitted. The method you are using will only add the value to the $_SESSION array for that page load – it won’t actually be in the $_SESSION array! Confusing right? So either of these won’t work…

$_SESSION[] = 'value or array';
$_SESSION[1] = 'some other stuff';

But this will, due there being text in the $_SESSION key (and don’t forget to start the session).

session_start();
$next = count($_SESSION) + 1;
$next = 'foo' . $next;
$_SESSION[$next] = 'bar' . $next;

This will generate the below for “print_r($_SESSION)”.

Array ( [foo1] => barfoo1 [foo2] => barfoo2 [foo3] => barfoo3 [foo4] => barfoo4...

Answer by Starx

Most simplest way of adding form values would be

$_SESSION['form'] = $_POST; //once the form is posted

Then access the values using

$_SESSION['form']['fieldname'];
Read more

PHP performance when printing

Question by Joel

Is there any difference between:

echo "<p>" . $var . "</p>";

and

<p> <?php echo $var; ?> </p>

when it comes to performance?

Joel

Answer by laurencek

The second is slightly quicker as it doesn’t have to concatenate the strings together.

But really you’re only going to see an increase in performance if this is repeated a huge number of times.

Also, as a slight side point, using the multiple parameters of the echo function, such as:

echo("<p>",$var,"</p>");

is also quicker than concatenating the string.

Answer by Starx

Even faster is this

<p><?=$var?></p>

Using <p> <?php echo $var; ?> </p> than echo "<p>" . $var . "</p>"; reduces server side operation. Even though in this case it is neglegible, it does have a difference.

Read more

Clear a two dimensional session array

Question by acctman

I’d like to clear a specific session, how would I go about doing that.

$_SESSION['files'][]

Answer by Haim Evgi

if you want to unset all the array is :

unset ($_SESSION['files']);

if you want only specific entry to unset is

 unset ($_SESSION['files'][entry]);

Answer by Starx

On addition to above answers, you can remove multiple session variables at once.

unset($_SESSION['file'],$_SESSION['image'],$_SESSION['video']);
Read more
...

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