• Basic PHP & MySQL Part 1

    by  • February 3, 2012 • Linux, MySQL, PHP • 0 Comments

    PHP and MySQL are two unique open source projects. While PHP is an excellent programming language, MySQL is the Database choice of millions of softwares, websites and companies out there.

    In this series, we will look at how to use PHP to connect and manipulate data stored inside MySQL. In the first part, I am going to demonstrate how to connect to a MySQL database and read data from a table and display the results.

    For this we need to first install Apache, MySQL and PHP. We will also create a database and a table in MySQL. If you haven’t done this earlier, follow the below shell commands.

     

    Remember to set a password for root user when asked. Also use the same password for the mysqladmin command. Now it is time for us to login to MySQL as root and create a table. We will also create a user in MySQL with less privileges to use that database and table. It is not wise to use root access in your applications as it would lead to lot of destruction if someone was able to crack/hack your application. We will also populate one sample entry in our table for PHP to read.

    Here is what I did on my terminal.

    Ok. Now we are all set to start with our PHP code. Make sure that Apache is running by browsing to http://localhost in your computer. You should be seeing a “It Works !” page. We will also create a test.php file in the root directory of  our web server and assign rights to our user so that we can edit it.

    Open this file ( /var/www/test.php ) your favorite text editor and paste the following code.

    Now open your browser and open the url http://localhost/test.php . You should be able to see the page below !.

    This was only about reading just one row of data from the example table. In the next part, we will look at how to read multiple rows and display the results as a HTML table.

    Hope you enjoyed this article. Feel free to try, share and discuss.

    Related posts:

    1. Beginning PHP

    About

    Could be found playing with his son Aryan when not working as a sysadmin. Likes to watch movies, play football, listen to music and chat with friends.

    http://www.undan.co.in

    Leave a Reply

    Your email address will not be published. Required fields are marked *