...

Hi! I’m Starx

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

mysql SELECT a whole column or cycle through all IDs

Question by Jordashiro

I need to select a whole column.
So my question is how do i get a whole column ?

        $query  = "SELECT * ";
        $query .= "FROM employees ";
        $query .= "WHERE id=*";
        $query .= "ORDER BY id ASC ";

I tried id=* but no luck …
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.

EDIT:

function get_all_ids()
    {
        global $connection;
        $query  = "SELECT * ";
        $query .= "FROM employees ";
        $query_result = mysql_query ( $query , $connection );
        confirm_query($query_result);
        $query_result_array = mysql_fetch_assoc($query_result);
        return $query_result_array;
    }

i use this to print the array

  $all_id = get_all_ids();
// preparing the table;
    echo "<pre>";
    print_r($table);
    print_r($all_id);
    echo "</pre>";

and this is the array

  Array
    (
        [id] => 1
        [department_id] => 1
        [name] => jordan
        [EGN] => 9108121544
        [email] => testEmail
        [address] => testAddress
        [country] => testCounty
    )

Answer by Linus Kleen

If there’s more than one row in your result set, you need to keep fetching until all results are retrieved:

$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);

If you’d like to retrieve all ids in a single fetch, you could do:

$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);

$list_of_ids = explode(',', $row['id_list']);

WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.

Answer by Starx

If you want to select a single column. Then do not use “*”, give the name of the columns name separated by comma and quoted with “`” (tick) for safety.

$query  = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
Read more

Padding Between "display:table-cell"

Question by user1152440

Is there a way to place padding or a transparent border around the “cells” when one does display:table-cell? I would like the background to show up through this space, so I can’t just set the border to white, and border-color:transparent doesn’t work for me for some reason. I’ve checked w3schools and similar sites but I haven’t been able to find this particular trait.

From user Praveen Vijayan: http://jsfiddle.net/geymU/

Answer by Starx

Use border-spacing: 10px on the parent container.

In your case

#nav ul{
    display:table;
    width:100%;
    border-spacing: 10px;
}

You can also give top/bottom and left/right separately like border-spacing: 10px 20px;

Read more

Difficulties with storing links in a mysql database?

Question by Matt Williams

Im trying to store some links in a database but i think my SQL code is off but i cant figure out what the problem is.

INSERT INTO `users`(`fbid`, `meme`) VALUES (122321414, http://google.com)

I think its the : character but im not sure how to escape it in SQL

If you could post anything to help me then thanks a lot! 😀

Thanks Everyone

Answer by Starx

You should escape the values, when entered into the database.

Use mysql_real_escape_String() to escape such values and never forget to enclose the values with a single-quote(‘), keeps you safe most of the time.

$url = mysql_real_escape_string("http://google.com");
$query = "INSERT INTO `users`(`fbid`, `meme`) VALUES (122321414, '$url')";
Read more

How defined in jQuery was it a regular click on the same element or double-click?

Question by Denis Masster

How i can defined in jQuery was it a regular click on the same element or double-click?

For example we have element like this:

<div id="here">Click me once or twice</div>

And we need to perform different actions after regular click and double-click.

I tried something like this

$("#here").dblclick(function(){
    alert('Double click');
});
$("#here").click(function(){
    alert('Click');
});

But, of course, it doesn’t work, everytime works only ‘click’.

Then, some people showed me this:

var clickCounter = new Array();
$('#here').click(function () {
clickCounter.push('true');
setTimeout('clickCounter.pop()', 50);
if (clickCounter.length > 2) {
    //double click
    clickCounter = new Array(); //drop array
} else {
    //click
    clickCounter = new Array(); //drop array    !bug ovethere
}
});

Here we tried to set the interval between clicks, and then keep track of two consecutive events, but this have one problem.. it doesn’t work too.
So, someone knows how to do this? or can someone share a link to the material, where i can read about it?

Answer by Chris Pratt

From QuirksMode:

Dblclick

The dblclick event is rarely used. Even when you use it, you should be
sure never to register both an onclick and an ondblclick event handler
on the same HTML element. Finding out what the user has actually done
is nearly impossible if you register both.

After all, when the user double–clicks on an element one click event
takes place before the dblclick. Besides, in Netscape the second click
event is also separately handled before the dblclick. Finally, alerts
are dangerous here, too.

So keep your clicks and dblclicks well separated to avoid
complications.

(emphasis mine)

Answer by Starx

What you are doing in your question, is exactly how it should be done.

$(".test").click(function() {
      $("body").append("you clicked me<br />");
});

$(".test").dblclick(function() {
      $("body").append("you doubleclicked me<br />");
});

It works and here is an demo for that.


Since, you want to detect separate single double click. There is a git project for this.

$("button").single_double_click(function () {
  alert("Try double-clicking me!")
}, function () {
  alert("Double click detected, I'm hiding")
  $(this).hide()
})

It adds up events to detect single double clicks.

Hope it helps you now.

Read more

Text layout issue with div inside of annother div with a fixed width

Question by jdln

I have a div.one which has a fixed size and a background color. Within it is another div which starts off hidden but is shown with javascript in certain circumstances.

How can I make it so when div.two is shown, you can see its background color and the text doesn’t wrap? Basically I want it to behave like it doesn’t have a containing div with a fixed size. Is this possible? Thanks

<div class="one">
  <div class="two">
    Some Text
  </div>
</div>

.one {
  width: 20px;
  height: 20px;
  background-color: white;
}
.two {
  background-color: grey;
  display: none;
}

Answer by bookcasey

Demo

.two {
    display: inline-block;
    background-color: grey;
    white-space:nowrap;

}

Answer by Starx

Fix the dimension of the div as well to 20px and 20px, and set the white-spacing to nowrap.

.two {
  width: 20px;
  height: 20px;
  white-space: nowrap;
  ...
}

Check out this demo to see if I solved your question.

Read more

How can i call a sub_page.php inside a div container of my main_page.php?

Question by Lucas Matos

I need to show the content of one of my sub_page.php inside my main_page.php

At the moment im using an iframe to do that, but i would like to show the sub_page.php inside a div, so it will have a more professional look.

How can i do that?

<HTML>
 <HEAD>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />   
 </HEAD>
 <BODY>
<div style="text-align:center;"><img src="faq-banner.png" /></div><br />
<div>
<?php include("faq.php"); ?>
</div>
 </BODY>
</HTML>

Answer by Starx

Inside the div, include the php page with simple include() command.

<div>
<?php include("subpage.php"); ?>
</div>
Read more

Is using a for-loop on submitted POST data in PHP safe?

Question by ACobbs

I’m always a worry-wart about security in my PHP applications, and I just (potentially) thought of a way a hacker could kill my script. Currently my application takes form data and submits it as an array to a PHP script via AJAX, then loops through this array.

foreach($_POST['form_data'] as $field => $value){
   //Do something here.
}

However, what if a hacker were to forge an AJAX request, and repeatedly submit the ‘form_data’ array with 100000000000 random elements? The loop would have to iterate through each element, possibly causing a DoS (or at least slow down service), correct?

I’m not entirely educated here, so I may have some incorrect assumptions. Thanks for any input!

Answer by NikiC

This will not be an issue: PHP limits the maximum number of POST vars using the max_input_vars directive, which defaults to 1000 variables.

This limit is actually enforced to prevent a much more serious type of DOS attack than the one you are thinking about (really, iterating a few thousand array elements is like nothing), namely hash table collision based attacks (often referred to as HashDOS). For more info on that issue see my article Supercolliding a PHP array.

Answer by Starx

Yes, ofcourse the hacker might sent all those datas, and it will definitely be unwise to iterate through them all. Could do many unexpected things.

I will suggest you trim down your application to only those, which is accepted. What you are doing now is taking all the values from the form_data.

Instead of this, you should know what values to expect. Could be something like name, address, phone and only iterate through such known values.

Thus, The problem that might occur will be reduced but not completely blocked. With additional size check, like Pekka suggested, you will trim down the risk even more.

Read more

jquery button fade with background image acting strange

Question by Sackling

I am trying to make a button fade into another class by using the toggleClass method. This seems to work fine until I introduce a background image into the classes.

I’m not even sure what it is doing exactly.. It seems to depend on where the mouse is on the button. Anyways the button sort of starts the fade, possibly where it is just the background color not image, and then just “pops” in the background once it completes the animation. I recreated it here:

http://jsfiddle.net/2YbqH/1/

So my question is.. how can i make the whole thing fade?

Answer by Starx

Yes, you can’t fade into classes, but it is POSSIBLE with a trick

$('button').on("mouseenter",function(){
     $(this).fadeOut(100).toggleClass("ui-state-hover").fadeIn(100);
});

Here is a demo. Basically, the idea is to fade out, then toggle the class and show again.

Check this demo to fake a background, when the button are fading out and in. I hope you will be do what you want from these demos.

Read more

How to echo a php array for dynamic javascript

Question by ToddN

I am using Google Analytics API to pull Total Visits and put into Googles Javascript to display in a bar graph. I am having issues trying to put an array to the variables. When I do a print_r it spits out everything just fine but I need it to spit out everything just as it is. This is what I got so far:

//I connect to my own SQL database for $num

//Connect to Google Analytics
$mystart = '2012-02-28';

$i=0;
while ($i < $num) {

        $ga->requestReportData(ga_profile_id,array('source'),array('visits', 'visitBounceRate'),'-visits', $filter, $mystart, $mystart);

//adds +1 day to date 
$mystart = date('Y-m-d', strtotime("+1 day", strtotime($mystart)));

$totalvisits = $ga->getVisits();

//These are my arrays  
$adddate[] = "data.addColumn('number', '" . $mystart . "');";
$addvisits[] = "$totalvisits,";
        }

This is what I am trying to achieve through the use of echos:

<script type="text/javascript">
      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Date');
        // This is where I want to put something like <? echo $adddate ?> but of course doesn't work
        data.addColumn('number', '2012-02-28');
        data.addColumn('number', '2012-02-29');
        data.addColumn('number', '2012-03-01');
        data.addColumn('number', '2012-03-02');
        data.addColumn('number', '2012-03-03');
        data.addRows([
        // This is where I want to put something like <? echo $addvisits ?> but of course doesn't work
          ['Feb. 28 to March 3', 100, 105, 91, 80, 150]
        ]);
</script>

Answer by Ynhockey

If you are asking how to output the array in the way you want, then use something like:

echo implode("rn", $adddate);

See implodeDocs.

Answer by Starx

Of course, it will work, you cannot echo an array. The easiest way is to implode them

Use these codes, where you are echoing them right now

echo implode("",$adddate);
echo implode("",$addvisits);
// User rn to implode if you need to add linebreaks
Read more

parameter passing between two classes in two different files

Question by Aragorn

i want to ask how to pass parameter between two classes in two different files?
ex:

class a{
  function aa(){
    $var1 = 10;
    return $var1;
  }
}
//in different file
class b{
  function bb(){
    echo"$var1"; //how this can be achieved?
  }
} 

Answer by Starx

None of the answers here are right, since the op is asking to pass the parameter and not call it. The correct way to do it, is by creating an object of class b

class a{
  function aa(){
    $var = 10;
    $obj_b = new b(); //create an object of the class b
    $b -> bb($var); //pass the $var value to bb method of class b
  }
}

//in different file
class b{
  function bb($var){
    echo $var;  //now your values is passed here
  }
}
Read more
...

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