MySQL – Connecting, Selecting…. and more.

Today I am going to show you various things that you can do with MySQL using PHP.
I am going to assume you have fairly good knowledge of PHP while following these instructions.

Connecting to MySQL

Connecting to MySQL is extremely simple. I am going to presume you know your MySQL credentials, if you don't know them, find them out 😉 .


$databasehost = "localhost"; //put your MySQL host into this variable. It is usually localhost
$databaseusername = "root"; //put your MySQL username into this variable.
$databasepassword = "somethingreallydifficulttoguess"; //put your MySQL password into this variable.
// I have used long variable names because the likelihood of them being overwritten is unlikely.
$conn = mysql_connect($databasehost,$databaseusername,$databasepassword) or die (mysql_error());

And thats it. In the event that your credentials are incorrect and error will be produced.

Creating a MySQL database using PHP

Creating a database in PHP is extremely simple.


mysql_query("CREATE DATABASE `database_name`",$conn) or die (mysql_error());
//this will create a database called "database_name" and use the connection we established earlier to create that database.

Selecting the MySQL database

Selecting the MySQL database is even simpler. Once you know your database name you can use this code to select the database:


$databasename = "database_name"; // the name of the database you want to select.
mysql_select_db($databasename,$conn) or die (mysql_error());
//the database you created earlier is now selected. If you already have a database created, you do not need to run the CREATE DATABASE code obviously.

Creating a MySQL table within a database

Things start to get a bit more complicated when it comes to creating tables. You may want to look at the MySQL website to get some more information on how to create tables using SQL.

Here is how we would create a table called "new_table" in the database.


mysql_query("CREATE TABLE `new_table` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(25),`age` int, PRIMARY KEY(id))",$conn) or die(mysql_error());

This code will create a table with 3 fields in (id - which is the primary key, name which allows up to 25 alphanumeric characters and age that allows an integer) .

Retrieving data from a MySQL table

I am going to show you a basic way of getting data from a table when you know all the field names of that database.
There are numerous ways of doing this (look into mysql_fetch_assoc() and mysql_fetch_array())


$select = mysql_query("SELECT `id`,`name`,`age` FROM `new_table`") or die (mysql_error());
if (mysql_num_rows($select) > 0)
 {
 while (list($_id,$_name,$_age) = mysql_fetch_array($select)) //gets the data from the SELECT query and puts it into variables
  {
   echo "The ID for this record is: " . $_id . "\n";
   echo "The Name for this record is: " . $_name . "\n";
   echo "The Age for this record is: " . $_age . "\n";
  } 
 }
else
 {
 echo "There are no records to display";
 }

The above example is the way I sometimes chose to do my SELECT queries because it is quite self explanatory with the variables. I would not recommend this method however if you have a lot of variables in your script as it could pose problems with overwriting variables.

This is another way of performing the same query:


$select = mysql_query("SELECT * FROM `new_table`") or die (mysql_error());
if (mysql_num_rows($select) > 0)
 {
 while ($row = mysql_fetch_assoc($select)) //gets the data from the SELECT query and puts it into the $row array
  {
   echo "The ID for this record is: " . $row['id'] . "\n";
   echo "The Name for this record is: " .  $row['name'] . "\n";
   echo "The Age for this record is: " .  $row['age'] . "\n";
  } 
 }
else
 {
 echo "There are no records to display";
 }

The above does the same thing as the example beforehand, but utilizes only one variable.

Deleting data from a MySQL table
The DELETE query is extremely simple. You simply define the table from which you'd like to delete a record, and specify a record. In this case we are specifying the record with an id of 1.


$del = mysql_query("DELETE FROM `new_table` WHERE `id`= '1' ",$conn) or die(mysql_error());
if (mysql_affected_rows() == 1)
 {
 echo "Record Deleted";
 }
else
 {
 echo "There was a problem deleting the specified record.";
 }

Dropping a table from a MySQL database
If you would like to remove a table and all its data from a MySQL database then use the following code:


$drop = mysql_query("DROP TABLE `new_table` ",$conn) or die(mysql_error()); 
  if($drop)
   { 
    echo "new_table has been dropped from the database.";
   }

Inserting data into a table
Inserting data into a table is extremely simple.


$insert = mysql_query("INSERT INTO `tblname` (`name`,`username`,`email`) VALUES ('Andrew','papa_face','someone@somewhere.com')",$conn) or die(mysql_error()); 
  if($insert)
   { 
    echo "The record has been inserted into the database.";
   }

Of course you can make insert queries dynamic by using variables, but that is one quick and easy example of how to insert data into a table 🙂 .

And that's it!
I hope this blog post have been very informative. Any questions or comments are greatly appreciated.
Thanks for reading!

Posted in Coding | 2 Comments

Sanitizing $_POST and $_GET

Hey,
Well I haven't posted something PHP related for quite a few days now so I thought I'd show you something I use in every single script that I write that involves form submissions or URL data.
It is important to escape (sanitize) all data from forms that may be used in a mysql database query.
If you use some other database type, the function can easily be modified.

Place this code at the top of all your pages (maybe via an include):


	if(!function_exists(mysql_real_escape_array))
		{
	function mysql_real_escape_array($t)
			{
	return array_map("mysql_real_escape_string",$t);
			}
		}

	mysql_real_escape_array($_GET);
	mysql_real_escape_array($_POST);

It will automatically sanitize all your $_POST (from forms) and $_GET (URL data) to help prevent SQL injections.

Be aware though, that this is just one precaution you should take when inserting data into a mysql database.

Posted in Coding | Tagged , , , | Leave a comment

FORTRAN and Other Programming Languages from the 50’s

FORTRAN-FORmula TRANslating system was invented in the year 1957. The language was very easy to use as it contained limited commands like GOTO, IF and DO. FORTRAN paved the way for today’s languages as it contained basic data types like integer, double precision, logical variables and real numbers which are very much used in today’s languages.

As in those days people were only looking for solving mathematical operations via programming languages, FORTRAN was a result of that need. This is why FORTRAN was amazing with numbers but was not the same in other areas, like handling input and output. As a result the language was not famous amongst businesses. When computers started getting into the businesses in the year 1959 A.D. the need for another language arose.

This is why COBOL was invented. From the beginning itself, COBOL was developed as a businessman’s language. The language was easier than FORTRAN to understand as it had only two types of data types; strings and numbers. The main feature of COBOL was to handle records, as businesses needed to keep an account of previous records. COBOL statements were related to the English language. This made it very easy for the businessman to get the grasp of the language better and they were able to adapt it easily.

In the year 1958 A.D. a new type of language was designed. It was called LISP-LISt Processing language. The main reason for the invention of this language was to explore the field of artificial intelligence. Syntax of the language was different from all the existing languages as the language dealt with a completely new area of concern. As the name suggests, the program in the LISP language are written as a set of lists that represents series of items. As a result of this the LISP programs have a distinctive ability to modify itself from time to time and consequently to develop on its own.

Posted in Coding | Tagged , , | Leave a comment

Programming on Electronic Devices

Computers cannot interpret human languages. They have their own language which is known as binary language. It is the language of 0’s and 1’s. So to command or program a computer to get the desired results one had to first convert the program from human language to the binary language. This was done by converting each line of the program into binary language and feed it into the memory line by line. This was how the computers in those days were programmed.

Shortly after the invention of John Von Neumann’s models, the first ever programming language to be programmed on an electronic device named Short Code was devised in the year 1949 A.D. In this language human help was needed to convert the program into binary language and feed it into the memory. This job of converting the program line by line into binary language was proving to be a tedious and time consuming work.

This is when the compiler was invented. The first compiler was named A-0 by its inventor, Mr. Grace Hopper in the year 1951 A.D. A compiler is a program which automatically converts the human language into the machine understandable language that is the binary language. The invention of the compiler made programming simple and very efficient. Now a lot of time was saved as the machine could itself translate human language into the machine readable language and the programmer was saved from the tedious job of interpreting.

In the year 1957 A.D. the first major programming language which appeared due to the inventions and work of earlier scientists was FORTRAN-FORmula TRANslating. This programming language was invented by International Business Machines (IBM). They invented FORTRAN for computing science related queries. The language was a breakthrough in programming. It was a big step towards the start of making high end languages. Today FORTRAN is nothing compared to modern languages because it contained limited commands such as DO, GOTO and IF statements, but these commands were innovative in those days.

Posted in Miscellaneous | Tagged , , | Leave a comment

How It All Began…

The traces of programming can be found as early as 2000 years ago with the invention of Abacus, a device made of wood which had two parallel strings fixed horizontally on it. On these strings, beads were embedded. Using programming rules which were decided by the scholars of those days, addition and subtraction of numbers was made possible using Abacus. Another significant programming development which was invented around the same time is the Astroble. This device proved to be very useful for navigation in those days.

These instruments, Abacus and Astroble were used significantly for many centuries until the discovery of the digital computer or in simple terms, a calculator by which it is known popularly was made. The famous mathematician Blaise Pascal is known for programming the first calculator in 1642. The device build by Pascal used to take numbers as inputs and used to give their addition as output. Pascal programmed the device in such a way that the numbers had to be entered via dials. Pascal invented this device in order to help his father save time in his calculations as he was a tax collector.

In the year 1671 A.D., a scientist named Gottfried Wilhelm Von Leibniz designed a computer. He claimed that his designed computer would be able to perform mathematical operations such as addition and subtraction and after making some modifications he was convinced that it could also perform multiplication. Due to financial crisis he was not able to convert his designed model into a reality. But he didn’t lose hope and in the year 1694 he was finally able to prove his design. He successfully programmed a computer that could perform the mathematical operations which he had claimed 23 years ago.

The programming techniques invented by Leibniz and Pascal were not accepted by their colleagues. Their inventions were considered weird for almost a century. But they were soon accepted by the new age scientists for making faster programming techniques and till today we use the same technique which they invented centuries ago.

Posted in Technology Stuff | Tagged , , | Leave a comment

John Von Neumann’s Two Programming Models

In 1945 a revolutionizing concept was invented which would change the way programming was performed. A scientist named John Von Neumann working at the prestigious Institute for Advanced studies in Princeton, New Jersey created two programming models. John named the models as “Shared Program Technique” and “Conditional Control Transfers”.

John was very concerned about the fact that the ENIAC was a success even though it used a lot of technology that was similar to the previous technologies. The ENIAC was a computer that had a complicated structure and was of undefined physical dimensions. Sometimes the computers were so large that they would occupy an entire floor. John suggested that a computer should have a simple structure and its size should be smaller than usual.

This is what John has tried explaining in the “Shared Program Technique” model. He created awareness among people that a computer need not be as large as they used to be at that time. He also told them that a computer can be a lot faster if they are programmed in a complicated structure instead of the simple mechanism that was used to design them those days. These ideas gave way to the high speed computers of today’s generation.

The main idea behind this kind of programming was to keep the computer busy all the time. As the computers of those days used to perform a single operation at a time and then used to enter wait state till the next instruction is received. So with the help of “Shared Program Technique” subroutines were created which helped in programming the computer so that it will be in busy state most of the time for the optimum utilization of the processor.

In the second model viz, “Conditional Control Transfer”, John informs us that instead of performing the program in a specific sequence i.e. line after line, there should be use of jump statement. He also suggests the use of conditional programming which is popularly known by IF-ELSE loop in today’s world. With the help of these two models the computers became much more efficient and

Posted in Miscellaneous | Tagged , , | Leave a comment

The First Programming Language

The first ever machine which calculated the difference between numbers was developed by Charles Babbage. This machine evolved with time and is called a computer nowadays. The machine which Charles Babbage invented used to perform only one operation i.e. calculating difference between numbers. This instruction which tells the machine that it has to calculate difference between two numbers is called programming.

Earlier programming languages were a lot different than today’s. In those days the programming languages were to be embedded line by line into the processor and then execute. They were able to execute only one program at a time as the memory available was minimal. Programming languages of the previous five decades have arrived in two phases; namely primary major language and secondary major language. The latter one is what we use nowadays.

The machine that was developed by Charles Babbage used gears for executing the calculation i.e. Charles’ difference engine was only useful if the gears were changed physically. The computers of yesteryears used physical motion for the execution of programs. This method changed in 1942 with the invention of ENIAC. ENIAC was developed by the US government who were successful in replacing the physical motion by electrical signals. In the new machine’s working many of the principles were same as Babbage’s. The only way the mechanism could be programmed was by resetting the controls and rewiring the complete structure, which was very tedious.

In 1945, the Institute of Advanced Study developed two significant models in the field which straightforwardly changed the way coding languages worked in those days. The project was headed by John Von Neumann who was working at the institute. The first model was named “The Shared Program Technique” by the Institute. John named the second model as “Conditional Control Transfers”. These two models were about to change the entire system of programming in those days and give way to new age programming concepts.

Posted in Miscellaneous | Tagged , , , | Leave a comment

The Basic: C Programming will always be popular

C is a general purpose computer coding language which works closely with hardware. C was invented by Dennis Ritchie and Ken Thompson with the help of their team mates at AT&T Bell Lab’s USA in the year 1969 but major development was made in the language in the year 1973 when it was actually published under the title “The C Programming Language”, the same year.

One would wonder why Dennis and Ken named the language as C. The reason is that in the process of developing the language they had taken a lot of features from the existing language which was called B. So the language which they created was an advanced version of the B language, which is why they named their language C, funnily.

C is a basic language which is the building block of mostly all the languages present today. The language is platform independent. That means C does not need any specific platform for running. It can work on any operating system. There are many compilers which run C. As the language works close to the hardware it uses minimal space. Also the language is easy to understand as it has a user friendly language.

If one wants to become a programmer, this is the first language he should learn. Also nowadays in academics, this language is made compulsory in computer studies. All the new languages like Java, Microsoft .Net and many other languages have used C language as their building mechanism. All these languages are easy to learn if one has knowledge of the C language.

The boundary of C language is vast. It s not limited to just programming of applications. In fact it is also used in graphical applications. There are many games which uses high end graphics built using the language. The C language is so old compared to modern languages but despite that it still it stands apart from all these powerful languages.

Posted in Miscellaneous | Tagged , , | Leave a comment

The Beginning of PHP

PHP – Hypertext preprocessor is basically a computer coding language. The language was designed by Rasmus Lerdorf and was developed by the PHP group. PHP was created in 1994 by Rasmus Lerdorf to help maintain his personal homepage.

He had written a bunch of Common Gateway Interface (CGI) binaries via the C coding language and wanted to restore a trivial set of Perl scripts which he had been using to preserve his homepage by the CGI. He wanted to do this in order to check the traffic on his homepage. This later was released publicly as the first ever version of Hypertext Preprocessor on 8 June, 1995 named PHP/FI (Form Interpreter).

One would wonder why there is an extra letter P in the abbreviation. The reason being the language is initialized again and again, recursively and that’s why the abbreviation PHP. PHP is an essential, object-oriented language. PHP is extensively used as an all-purpose scripting language, which is particularly fitting for web development. The working of PHP is simple. PHP essentially uses a web server to run, which takes the PHP code as input and results in web pages as output.

PHP was originally created for designing dynamic web pages. Over the years the main focus of PHP has changed. Server side scripting is the spotlight of PHP now. Moreover PHP has been declared as free software by the free software association. It is available over the internet and any one can download it. Due to this reason PHP stands out in comparison with competitors like Microsoft’s ASP.NET system, mod_perl framework and Sun Microsystems’ JavaServer Pages as they are not free. The PHP parser can run with both, a web browser and a web server which help in providing dynamic content.
The following is a simple Hello World code example for PHP:


<?php
Echo ’Hello World!’;
?>
Posted in Coding | Tagged , , , | Leave a comment

PHP – The Basics – Tags, echo and if/else

One of the most basic things when writing code in PHP is to use the PHP tags which signify the beginning and the ending of the PHP code. You must have the tags in order for PHP to process the code you write. The tags are:

beginning tag:

<?php

ending tag:

?>

e.g


<?php
//code here
?>

You can have anything proceeding/preceding the PHP tags, but anything in between them must be valid PHP.

I advise you to only use the tags that I have stated above. Try not to use tags like:


<? 
//some code
?>

or


<?= "Hello!" ?>

Shorthand tags are not 100% compatible on 100% of servers, however:


<?php
//some code
?>

is! 😉

We’ll start with something pretty simple and it is the echo statement.
This is an example of the echo statement:


<?php
echo "Hello you!";
?>

When the script is run, the page will display “Hello you!”.
Notice the semicolon? The semicolon (;) is a line terminator. It tells PHP that you are finished with that particular set of instructions, and that PHP can continue with the script until it reaches the end. If the semicolon is not present at the end of instructions/commands/statements/variables a error may be triggered as a result.

Now lets move on to something a little more useful, the if/else statement.

This is an example of an if/else statement:


<?php
if (5 > 10)
 {
 echo "5 is greater than 10";
 }
else
 {
 echo "5 is not greater than 10";
 }
?>

Okay with an if statement you must define the conditions of the if between the brackets. The aim of an if statement, is to get true returned (a boolean). If the condition returns false, then it will run the code in the else statement (if there is one).

In the code above the if statement will return false and display “5 is not greater than 10” – understand?

Yeah its pretty easy at this level.
If I used this code:


<?php
if (5 < 10)
 {
 echo "5 is less than 10";
 }
else
 {
 echo "5 is NOT less than 10";
 }
?>

The if statement would return true, and therefore we would get “5 is less than 10” printed out on the page.

When writing an if statement there are two important parts.

  1. The condition – this is contained in between brackets (5 < 10)
  2. The curly braces – { } – the code you want to execute should be placed in between the two curly braces. The only exception to this is when you only have one line of instructions like this:

<?php
if (5 < 10)
echo "5 is less than 10";
?>

That concludes this part of my help guide I hope it was useful to those starting to learn PHP.
If you want to look into the if/else statement more, look into elseif. The PHP manual is a great resource, so make good use of it. It contains everything you need to know about PHP (literally).

Feel free to comment on this post, I appreciate all the comments I receive! 😀

Posted in Coding | Leave a comment