PHP/MySQL Querying Using SELECT

PHP/Mysql & SELECT

We have been looking at SELECT statement for sometime and I would like to apologise in advance but we are going to have to go through it again in this article. However , we are not just going over how to query rows and columns using SELECT , we are going to look at it from PHP language point of view and see how we can return those rows into a webpage. Of course , I am simplifying the whole process slightly because there will be topics we won’t be going into such as pagination. Perhaps in future. If you have forgotten all about SELECT statement , here is the link to my previous article explaining it in more details.

Lets take a brief look at the SELECT statement and this is how the syntax should look ,

SELECT column_name(s)
FROM table_name

This is how the whole PHP/MySQL SELECT works ,

$con = mysql_connect("host-name","user-name","user-password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("database-name", $con);

$result = mysql_query("SELECT * FROM Employee");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "";
  }

mysql_close($con);

Of course we have been looking at “mysql_connect” function too many times. So if we are to remove all those items that are not necessary to our objective and view only those that are important items , this is what we been talking about all this time ,

$result = mysql_query("SELECT * FROM Employee");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "";
  }

First we send a query , take note that unlike C# , all that PHP does is to send a command , a string , to the MySQL database. It has no control over how MySQL handles it or whether it is even a legal SQL statement. Then it passes the resultant array to the $row and using while loop , it goes over the entire array printing the result in each new line HTML BR. It is similar to “Console.WriteLine” except you need to specify the new line explicitly.

SELECT Statement Conclusion

I think this should do for now to the PHP/Mysql side of the tutorials and tomorrow onwards , we go back into C#. Mainly because this is what I will be doing in my part-time degree so need to concentrate more into C# rather than PHP. Perhaps , next time I can go into PHP again.

PHP Function | $_GET

As I said yesterday , I will be talking about $_GET function today. Of course , you should have an idea of what does $_POST do , if you have not , pls refer back to my previous post here. Today’s tutorial will be short because we have already gone through the major part of it , which is the web forms.

Lets do a short recap on the web forms. Web forms are those you need to fill up for user registration such as for this site or to leave a comment on blog sites such as blogspot.com. We are interested in how does the data goes from the page where you fill up the form to being inserted into the database. This is where PHP functions such as $_POST and $_GET comes in.

This article is about $_GET function. We have already talked about $_POST function yesterday so won’t be going over it. Pls refer back to the previous post should you need help on $_POST. So what is $_GET? Before we start talking about what function does it serve , we should take a look at its definition.

PHP $_GET Function Definition

The $_GET function is used to collect values in a form with method="get". It is built into the PHP Language.

I think we covered what it meant by being built-into the language directly so won’t be talking about it anymore. Lets take a closer look at what it means by “a form with method=”get”". Here is one such form ,

form action="newuser.php" method="get">
Name:

Age:


This is the exact same form that we have looked at before except the method now is “get” instead of “post”. So what is the big deal about get and post? Take a look at the result of “post” method.


http://www.sqlhack.net/newuser.php

And contrast it with the result of “get , which is handled by $_GET function.


http://www.sqlhack.net/newuser.php?fname=Jame&age=45

Do you see the difference? The name and age entered appears on the url. Imagine if it was transmitting , the user password. That would not be a very secure website. Of course , it is not just about passwords and such , maybe you just don’t want any data that you entered to be appeared on the url when you click submit button.

On the other hand , suppose you are watching a youtube video and would like to share it with your friends, you can imagine how useless it would be if youtube.com were using the “post” with $_POST function. As with most IT stuff , there is always pros and cons and it is up to the developer , you , to determine which function to use for which purpose. Ultimately , no matter how advanced the technology is , it is still the people that makes the final decision.

$_GET Function Conclusion

I hope this $_GET and $_POST tutorial that I did yesterday help you with your programming and hope you enjoyed it as much as I did. Cya!

PHP Function | $_POST

$_POST Function In Brief

Last post on PHP/MySQL , I mentioned a function called “$_POST” which is supposed to get the variables from the form in order to insert into the database. If you cannot find it on the front page , it is available here. I suggest you go through it one more time to see how the form collected some data from the user and passed it a php page to be processed. So today , instead of anymore PHP/MySQL , I thought I go over abit of $_POST to complete our understanding of PHP language in general.

So what is $_POST in the first place? It is used to collect values in a form with method=”post” such as the form we created last lesson. It is also built-in , meaning you do not need to add any header files or anything. Once you have PHP , it is already there for you to use. Now you might be thinking , there is “post” and there is also “get” in the forms , so what is the main difference?

Well , first of all , similarities. Both are PHP functions , $_POST and $_GET and both are used for the same thing in mind , meaning to send data from one page to the next. Here is the main difference , information sent from a form with the POST method is invisible to others. Lets take a look at one example ,


Name: Age:

When the user click on the “submit query” button , this is what he will sees on the url bar ,


http://www.sqlhack.net/newuser.php

This is especially useful if you are sending sensitive information across the pages such as username and password. This is definitely not useful if you are running a site such as youtube.com or flickr.com. Can you imagine every youtube videos have the same url? Surely this will be impossible to bookmark any one of them!

$_POST Function Conclusion

Of course, “get” will returns all the information posted , which will be covered tomorrow :P I hope this short tutorial on $_POST helped someone who is having troubles with php forms or those who are interested in PHP. Hope you enjoyed it and till next time , CYA!

PHP/MySQL For Beginners 2 | Inserting Data

Last lesson , we have looked at how to connect to the MySql database from PHP. Today , we will be continuing from it and see how we can insert data into the database.

Lets recap on the sql statement for inserting data into the database before we go into specific PHP codes. If you remember from the post I did a while back , there are two ways to inserting data into the database. First form does not states the column headers specifically , only the name of the table and values to be inserted. Here is the syntax of the first form ,

MySQL INSERT Syntax

INSERT INTO table_name
VALUES (value1, value2, value3,...)

And the second form with the column headers specifically named and the respective data to be inserted,

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

Either one should be fine unless there is a specific requirement. So how do we do the same in PHP?

PHP/MySQL Insert Example

$con = mysql_connect("host_name","user_name","user_password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("db_name", $con);

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");

mysql_close($con);

The only new statement here would be “mysql_select_db(“db_name”, $con);” which associate $con with the database name to be used. The rest of the statements should be very clear to you and I dont think there is a need to go further into them.

But you might be thinking , how do I get the data? Well , on the web , most data comes from the user , in web-forms such as registration forms and so on. Therefore , it is not unexpected to assume that our data will also come from some type of forms. I know we have not gone through PHP forms so I will be using a plain HTML form you can get it easily anywhere online

Here is an example of such a form ,

Firstname: Lastname: Age:

So lets look at the “insert.php” ,

$con = mysql_connect("host_name","user_name","user_password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "First Name , Last Name and Age Added to Database";

mysql_close($con)

The only thing new would be where the $_POST is. $_POST basically is a PHP function used to collect values in a form with method=”post” , which we just did in HTML.

PHP/MySQL Inserting Data Conclusion

Hope this tutorial helps someone with some basic idea about using PHP and MySQL. Cya!

PHP/MySQL For Beginners | MySQL

PHP & MySQL Introduction

For past 2 days , we have looked at C# and SQL integration using LINQ. The last lesson can be found here. You should have a general idea of how C# can access the RDBMS (Ralational DataBase Management System) and how it is built into the language itself. Today , we look at another language , PHP , and how we can do the same with it. Except that , PHP doesn’t have something like LINQ , you could add phpLinq class available here , but we are interested in how it is done natively.

PHP & MySQL Connection Example

Lets see the code for the php to connect to MySQL database.

$con = mysql_connect("hostname","username","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

There isn’t much to added to it except that “die” part. It is what is known as “exception handling” , if you have done Java or C++ , meaning that if the connection to the database isn’t successful , there will be an error message printed out to the user. Besides that , basically the connection to the MySQL database is stored in the variable called $con is all that we need to know for now. In the subsequent posts , I will be going into how we can use $con to access the tables and rows and also doing likewise for LINQ. Eventually we will be able to use both X# language and PHP to access MS SQL Server and MySQL databases.

By now you are beginning to see why I said it is much more convenient to access the database from C# using LINQ rather than from PHP. Of course , it doesn’t mean that it will be this way forever. PHP , being opensource , is always evolving and I am sure one day there will native methods in PHP that can access to database. Then I will be able to say how wrong I was.

But what if we no longer have the use for it? Can we somehow close the connection? Sure we can.

mysql_close($con);

Conclusion Of Php MySQL

Just like that. Simple and sweet heh? With one statement is all that you need to close the connection to the database Alright , thats all for today. Its a Monday and I am feeling lazy. Cya!

MySQL Users Management

MySQL System Database

A short break from the current discussion about programming. Lets go briefly into Users in MySQL. First of all , when you log into the MySQL database as a root user and then do this command ,

show databases;

You will see your created databases. One of them is by default , ‘mysql‘ database containing system information , including users. So lets use the mysql database.

use mysql;

Then we see what are the tables in the database ,

show tables;

MySQL Users

One of the tables listed is called ‘user’ which for obvious reasons , is the table containing the information regarding the MySQL users , including the default administrator. So what kind of information is in it?

desc user;

You would see that there are more fields than most of us would ever use in our lifetime. The three fields or column headers we would be most interested in are ,

  • Host
  • Username
  • Password

Out of the three , we would be most interested in ‘Password’ header to change user passwords. You could do it with normal UPDATE keyword ,

UPDATE user SET Password=PASSWORD('newpass')
  WHERE User='bob';
FLUSH PRIVILEGES;

MySQL Shortcut

The last line “FLUSH PRIVILEGES;” is to reset the settings , if you would like , for the database. Just remember to do it everytime you create or change passwords for users. But in MySQL , there is another way to do just that , much neater and shorter ,

SET PASSWORD FOR 'bob' = PASSWORD('newpass');

See I said neater and shorter. There is no flushing or anything else. Sweet! For more information , here is the official page.

Till I got time for more Mysql tutorials , Cya!

Changing user passwords in MySQL Database

Lets take a brief look at how to change a user password in MySQL Database.

mysql -u root -p

If you have set the root password for MySQL , this will prompt you with the password to log in as root. You should set root password if you havn’t.

mysql> use mysql;

To select the database to use , in this case mysql database , which is the administrative database for MySQL servers.

mysql> update user set password=PASSWORD("NEW-PASSWORD-HERE") where User='YOUR-USER-NAME';

Thats it! We have looked at UPDATE keyword recently , the only thing we havn’t is the password=PASSWORD() which calls the PASSWORD function to encrypt the string in it. Simple stuff!