Passing by reference in PHP

I was just reading up on some PHP while I work on one of my final projects and I came across the topic of passing by reference. Which if you are not familiar with it, this is the PHP.net reference page. I had no idea that it existed and it instantly reminded me of the past three weeks of C++ where we have been discussing and using pointers as a means of “returning” more than one value from a function.

A good explanation of a reference is:

“References are a way to have multiple variables referencing the same variable container using different names — so whatever name you’re using an operation on that variable will always have an effect on the others.” – Johannes Schl├╝ter

My experience with pointers and passing by reference has been in the classroom and so the only benefit I have seen is that you can modify variables outside of a function. Check this snippet out for instance:

function addOne(&$input){
$input++;
}
$var = 1;

addOne($var);

//returns 2.

Conclusion

I don’t know that I would really pass by reference outside of the classroom at this stage as I have not encountered a situation where I needed to return or modify more than one value at a time.

Google Ranking

Last week I was watching state of the index by Matt Cutts and he mentioned in the future Google may rank sites based on how quickly the page loads. So I decided to test my site.

The test

I ran my site through Web Page Test and got some astonishing results. I failed on almost every account! Not having a lot of time there were some suggestions I was able to take an implement easily. The first was to enable gzip. I had always though I would have to install some fancy script to do this so I found excuses not to do it. Now I know that is not the case. It can be enabled quite easily if you have access to your php.ini file or if you just want to include this nice little snippet at the top of your page!

ini_set('zlib.output_compression','On');

I was also told that I had too many css and js files included and it suggested combining them. Understandable, but how can one combine the core jQuery file and their main script file and have it still be maintainable? I compromised and combined my js script files that I wrote together.

The change

I am not sure if it is because of the simple changes I made or if it is because I have been writing a little more frequently, but my ranking has improved when searching on my name. I usually do a search for ‘Levi Jackson’ to see where I pop up and currently I am number 3 when I had been 7 or lower for the longest time. Regardless it has made me more interested in optimizing my web pages than I have ever been before.

The current stats

Speed test results
I still fail many of the tests! What I do plan on working on next is to figure out a method of combining all of my js files or perhaps getting rid of some of them. At the same time I am going to work on a method of caching content so as to not require a call to the db unless there has been a change to a file since the last visit.

Conclusion

If page speed isn’t factored into the ranking yet… it will be. It is better to fix it now when it doesn’t play a role than to find your site dropping in ranking and need to rig something together to fix it then.

Processes and threads – what’s the difference?

As I get further into .NET I feel I need to get a handle more and more on how a computer actually runs. Today as I was reading I came across and attribute of the @Page directive: AspCompat. The definitions I came across kept mentioning threads and processes.

AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but should be set to true in any ASPX file that creates apartment-threaded COM objects–that is, COM objects registered ThreadingModel=Apartment. That includes all COM objects written with Visual Basic 6.0. AspCompat should also be set to true (regardless of threading model)

Courtesy of: .net Funda

A process

  • Processes are instances of programs (applications).
  • Each process is allocated its own space in the memory and therefore there needs to be an additional step to communicate between processes (using pipes, and so forth).
  • Because each process runs in its own space in the memory, there is little chance of overwriting or corrupting data in process A from process B

A thread

  • Threads are components of a process.
  • Threads share memory and the various other system resources, this allows for easy communication between threads.
  • Not secure, a thread can write memory used by another thread.

Multiple processors

When you have a single processor and you decide to open up Chrome it begins a new process with a new thread. If while you are browsing in Chrome you open up iTunes another process and thread are created. When using a computer with a single processor such as the Pentium series the processes would appear to be working at the same time but in reality they would be alternating sending bits of info. With computer that are running with two or four processors, this would allow each processor to run its own program; one would run Chrome and one would run iTunes.

Multithreading

Multithreading is when you create a thread to run a command/task. The reason for doing this is that when you program using a single thread there may come a time when you require a large amount of information from an external source, such as a database or a server. When this happens it makes more sense to create a new thread and have that retrieve the information in the background. It allows the main application to continue running rather than pausing and waiting for the response from the external source.

Conclusion

Multithreading is something that I doubt I will run across anytime in the close future, but it is important to know how something works. For me learning has always been about researching the things people take for granted when learning a new language or program, such as the AspCompat attribute. Threading will also most likely come into play while I am learning C++ as well this semester.

Resources I used to write this.

How Google indexes flash elements

So in the past flash web sites were discouraged by almost any web marketer/SEO specialist you spoke to. Because of their nature, being in some ways a partial compiled image/video it was tough for Google or any other search engine to index anything from them. The best a person could do was include meta description and keywords tags in the html that surrounded the flash piece. This was not very efficient because early on many search engines placed low importance on those meta tags. They were and continue to be easy to stuff and manipulate with non relevant content.

How have Google, Yahoo, Bing responded to this need?

In June of 2009 Google announced they could index external content linked from a flash file. What this meant is that say a flash page is populated by an XML file. Previously that file as well as the page linking to it would be found and indexed all on its own and the content would be weighted by itself. What happens now is that the pages are connected – they share a rank essentially. Also on that page Google lists what they have accomplished with flash:


To date, when Google encounters SWF files on the web, we can:

  • Index textual content displayed as a user interacts with the file. We click buttons and enter input, just like a user would.
  • Discover links within Flash files.
  • Load external resources and associate the content with the parent file.
  • Support common JavaScript techniques for embedding Flash, such as SWFObject and SWFObject2.
  • Index sites scripted with AS1 and AS2, even if the ActionScript is obfuscated. Update on June 19, 2009: We index sites with AS3 as well. The ActionScript version isn’t particularly relevant in our Indexing process, so we support older versions of AS in addition to the latest.”

What is Adobe doing?

In the background Adobe is facilitating crawling of swf web pages. Adobe has provided algorithms that they use to create swf files so that they can be broken down and used by the major search engines to “crawl” the swf files.

Example

One way to see what Google has indexed flash wise with your site is to do a test query. Something like text_from_swf_file site:sitename.com. I did a query of pledge site:levijackson.net as I have a flash piece I did for a class on the Pledge of Allegiance. If you follow the link you will see the second link goes to my swf file. Which is pretty cool, although it doesn’t appear the text/letters have been ordered as they appear on my page. Either way whole words and sentences were indexed from the file!

Conclusion

It is still not advisable to make a key portion of a site in flash there are still limitations to how search engines index swf files. There is no doubt that Google is the most advanced search engine and to assume that Yahoo, Bing, or Ask are at the same level would not be a good decision.

Formatting external hard drive to FAT32

So what I found out tonight was that you cannot format an external hard drive over 100GB at least (probably a lot lower) with the Windows GUI. You need to take it to the command line to achieve format it. The steps I took to format a Seagate Freeagent are:

  1. Goto Start > Run
  2. Enter in CMD and press enter
  3. Type in format /FS:FAT32 DRIVELETTER: and press enter
  4. It may ask you to enter the volume label, just enter what it shows up as in My Computer when it loads up normally
  5. It will give you the final confirmation – press “Y” and hit enter

There you have it, sit back and enjoy a cold while you wait for the drive to finish.

Easy way to create a hyperLink in C#/.NET

I am taking a class on ASP.NET using C#. In my effort to figure out how it all works I decided to look at the initial default document created in Visual Studio and add in some basic items such as input boxes, radio buttons, and hyperlinks to see how to implement them.

The Basics

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FirstApp._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    <asp:Button ID="Button1" runat="server" Text="Button" ></asp:Button>

    <asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink>

    <asp:DropDownList ID="DropDownList1" runat="server">
    </asp:DropDownList>

    <asp:RadioButton ID="RadioButton1" runat="server" ></asp:RadioButton>

    <asp:BulletedList ID="BulletedList1" runat="server">
    </asp:BulletedList>
    </form>
</body>
</html>

It appears as though HTML has been replaced by a class in .NET. Which makes sense considering how many different ways a person can enter in the markup. If we take a closer look at the HyperLink element we can see more specifically how it works.

You will notice several attributes right away: ID, and runat. The ID works just like an id in CSS or Javascript, it is a unique way to identify an element or node on the page; if humans had id’s mine would be Levi. The second attribute, runat, is used to tell the page that the element is to be processed by the server. One thing that I wondered about at this point was where is the actual link?
Visual Studio HyperLink properties

The hidden attributes of HyperLink

  • AccessKey – Assign a keyboard key to the link.
  • TabIndex – Set how many times you press tab to get to the element.
  • ImageUrl – Want to use an image as the background?
  • NavigateUrl – Where the url is going.
  • Target – Whether to open the link in a new window/tab or the current window.
  • Text – Link text, ImageUrl overrides this.

So a hyperlink may look something like this:

<asp:HyperLink ID="HyperLink1" runat="server" AccessKey="w" 
        NavigateUrl="www.google.com" TabIndex="1" Target="_blank" >
     Hyperlink</asp:HyperLink>

Afterthought

Visual Studio seems like a good idea for someone starting out with C#. It useful in the same way Dreamweaver is useful for anyone beginning HTML. The code hints and resources built in allow the user to see all the possibilities without needing to know of them beforehand.

Delete rows from multiple tables

So I was puttering along with a project I came across a situation I have come across before. How to delete information from a table that is related, such as deleting a user, their profile, and any other information associated with said user. In the past I had just executed as many queries as it took to get the job done. This isn’t the best option though for one big reason.

Performance

The more results a query returns, the more system resources it uses. So executing multiple queries can often times end up with the server doing more work than necessary. So my suggestion is to create a multi-table query that narrows the results using the where clause.

Imagine a scenario where you had the following tables, keep in mind the tables are in no way what I would use for an actual site, they are far from being normalized:

CREATE TABLE `User_Info` (
  `User_ID` int(11) NOT NULL auto_increment,
  `User_Type_ID` int(11) NOT NULL,
  `User_Title` varchar(255) NOT NULL,
  `User_Address_ID` int(11)NOT NULL,
  `User_Profile_ID` int(11)NOT NULL,
  PRIMARY KEY  (`User_ID`)
  FOREIGN KEY  (`User_Address_ID`)
  FOREIGN KEY  (`User_Profile_ID`)
) ENGINE=MyISAM AUTO_INCREMENT=80 DEFAULT CHARSET=latin1;
CREATE TABLE `User_Address` (
  `User_Address_ID` int(11) NOT NULL auto_increment,
  `User_Address` varchar(100) NOT NULL,
  `User_Town` varchar(100) NOT NULL,
  `User_State` varchar(100) NOT NULL,
  `User_ID` varchar(100) NOT NULL,
  PRIMARY KEY  (`User_Address_ID`),
  FOREIGN KEY (`User_ID`),
) ENGINE=MyISAM AUTO_INCREMENT=80 DEFAULT CHARSET=latin1;
CREATE TABLE `User_Profile` (
  `User_Profile_ID` int(11) NOT NULL auto_increment,
  `User_Name` varchar(100) NOT NULL,
  `User_Password` varchar(100) NOT NULL,
  `User_ID` varchar(100) NOT NULL,
  PRIMARY KEY  (`User_Profile_ID`),
  FOREIGN KEY (`User_ID`),
) ENGINE=MyISAM AUTO_INCREMENT=80 DEFAULT CHARSET=latin1;

The acceptable solution

My old method would have had me doing multiple queries

DELETE FROM User_Info WHERE User_ID=1;
DELETE FROM User_Address WHERE User_ID=1;
DELETE FROM User_Profile WHERE User_ID=1;

The better solution

The better way to do this is of course as I said above using one query.

DELETE FROM User_Info, User_Address, User_Profile
USING User_Info
WHERE User_Address.User_ID = User_Info.User_ID
AND User_Profile.User_ID = User_Info.User_ID
AND User_Info.User_ID =  1;

If you are interested in learning other methods of doing multi-table deletes, check out this site that uses joins to accomplish the same result.

Copy info between database tables with one query

I was thinking about the future of my web site the other day. One of the questions I began to think about was, what if I decide to change to a different Content Management System (CMS)? Which was never really a problem before because I did not have much content to move over. In the past I had pages for my portfolio, about me, contacting me, and that is about it. Now that I have begun to write on my site as well, I now have to worry about how to preserve the content. The two areas I am concerned with are:

  • Moving data from one database to another.
  • How to handle URL rewriting so that my pages don’t suddenly go AWOL in search engines.

Set-up

Say you have an existing table in a database called DB1,

CREATE TABLE `Event_Info` (
  `Event_ID` int(11) NOT NULL auto_increment,
  `Event_Type_ID` int(11) NOT NULL,
  `Event_Title` varchar(255) NOT NULL,
  `Event_Date` varchar(100) NOT NULL,
  `Event_Address` varchar(100) NOT NULL,
  `Event_Town` varchar(100) NOT NULL,
  `Event_Desc` longtext NOT NULL,
  `Event_Inserted` varchar(100) NOT NULL,
  `Event_Updated` varchar(100) NOT NULL,
  `User_ID` int(11) NOT NULL,
  `Event_Pending` varchar(255) NOT NULL default '0',
  PRIMARY KEY  (`Event_ID`)
) ENGINE=MyISAM AUTO_INCREMENT=80 DEFAULT CHARSET=latin1;

You are tasked with moving over the id, title, town, and description to a new database/table to be used with a different application. I put together this test table to move the information into, it is located in a database named DB2.

CREATE TABLE `event_stuff` (
  `eventID` int(11) NOT NULL auto_increment,
  `eventTitle` varchar(255) NOT NULL,
  `eventTown` varchar(255) NOT NULL,
  `eventDesc` varchar(255) NOT NULL,
  PRIMARY KEY  (`eventID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Moving the data

So what we need to do is select the title, town, and description from Event_Info and insert it into event_stuff. The first step is to write a query that selects the data from Event_Info. In the past when I have transferred info between two tables I have used a subquery to get the values to insert. Something along the lines of this, INSERT INTO Table_One VALUES(SELECT field1,field2,field3 FROM Table_Two). I tried to set something like this up and ran into one problem, I am working not between tables but between databases.

The query

After reading some documentation on the MySQL site and spending a couple hours working out queries. I figured that I must need to reference the database somehow but I really could not find adequate information about it and so I finally gave in and went to Stackoverflow. There I found out that I didn’t need the schema files as I thought I might have and all I needed to do was reference the database. The final query that worked flawlessly for me was

INSERT INTO DB2.event_stuff (eventTitle,eventTown,eventDesc) 
SELECT t.Event_Title, t.Event_Town, t.Event_Desc FROM DB1.Event_Info t;

Something I learned from this query is that you can set an alias for a table after you use it! I had always been under the impression it was like PHP, PERL, ASP, etc… in that you needed to instantiate the variable before using it. I wonder if MySQL reads the whole query before executing it? Anyway, if you have any input let me know, if there is a more efficient way to do this with one query I would be interested to see that.

Part two will cover URL rewriting so there isn’t a loss in ranking with the search engines.

Link to outside page AS3

Linking out to a page not in your flash file is pretty simple with AS3. What you need to have set up before we continue is a button or symbol made. I will be using this one,

Step 1) Give your button a name. The name is used when scripting to reference the button.

Name the button

Step 2) Create a new layer for your scripts to go in.

New layer

Step 3) Select the first frame of the scripts layer and open the action window (The action window can be opened by selecting Window > Actions)

Step 4) Enter this into the action window

button_a.addEventListener(MouseEvent.CLICK,openPage);

What this does is to say, ‘anytime there is a button named ‘button_a’ check when it is clicked and fire the function openPage. We are going to set up the openPage function next.

Step 5) Define the openPage function.

function openPage(e:MouseEvent){
	var page:URLRequest = new URLRequest("http://www.levijackson.net");
	navigateToURL(page);
}

e:MousEvent is the parameter for the function. So when someone clicks on the button it will fire this function off.
The second line is where the url to go to is set. URLRequest is an object that accepts a url when it is instantiated.
The third line uses the function navigateToUrl to send the user to the new url.

Step 6) Save and export the file and test the button out.

Here is the final .fla file.

For some further reading on the navigateToUrl Function.

How to select input names that contain square brackets

Array of checkboxes.

I was working on a site where I needed to validate that at least one value from a set of checkboxes was checked. They were set like so:

<input type="checkbox" name="subCat[]" class="subCat[]" value="1" /> One
<input type="checkbox" name="subCat[]" class="subCat[]" value="2" /> Two 
<input type="checkbox" name="subCat[]" class="subCat[]" value="3" /> Three

I tried checking each of the inputs with a class of subCat[] by using the nice handy .each function in jQuery.

	$('.subCat[]').each(function(){
		alert('hey');
	});

The error.

When I ran the page I was greeted with a nice error within Firefox’s error console.

Error: uncaught exception: Syntax error, unrecognized expression: ]

The solution?

My first thought was that the square brackets needed to be escaped. So I tried escaping it like I do with PHP:

	$('.subCat[]').each(function(){
		alert('hey');
	});

Nope.

Still the same error. So I did some Googling and for the given error message I was told that the “@” was removed from jQuery 1.3 when referencing an attribute… A completely irrelevant answer for this situation. So I gave up searching and was about to post a question on Stackoverflow when I decided to keep trying to figure it out.

That is when I made one last search on Google and came up with this magnificent page.

The real solution

Turns out the solution is what I thought it was, to escape the square brackets. I just didn’t realize I needed to also escape the forward slash. So the final code that iterates through the input is:

	$('.subCat\[\]').each(function(){
		alert('hey');
	});

I hope I spared someone the time it took me to figure this one out.