Saturday, June 22, 2013

How to run a MySQL query using PHP

Simple tutorial!
Prerequisite Knowledge: Basic PHP, and MySQL
Prerequisite Stuff: A server that can run both PHP and MySQL(here is a simple way to set up the same on your system)

Step 1: Create a MySQL conenction!

  1. Define 3 string variables to define, the database host name, username and password
    • $dbhost = 'localhost'; //enter your hostname under quotes;
    • $dbuser='myuser'; //enter your database user name in the quotes;
    • $dbpass='mypassword; //enter your database user password;
  2. Create a MySQL connection using mysql_connect() function
    • $connection = mysqli_connect($dbhost,$dbuser,$dbpass);
    • if(!$connection) echo 'cannot connect to database'; //Checks whether connection is made

Step 2: Select the required database

  1. Define a string variable with database name:
    • $dbname='mydatabse' // Enter your name of database under quotes
  2. Select the databse using mysql_select_db() function
    • $select = mysqli_select_db($connection,$dbname) or die('cannot select database');
      • The die function checks whether the database could be selected or not

Step 3: Lets run the query

  1. Define a string variable for query.
    • $query = 'SELECT * FROM table'; //put your MySQL query in quotes
  2. Run the query using mysql_query() function.
    • $query = mysql_query($query)
    • We define the variable to get the result from MySQL.
Enjoy! Happy coding. Practice the code by understanding it. Yup, I did not include a sum up, understand and code it yourself! You can do it, trust me!

More coding at Let's Code!
Edit: Modified with mysqli extension. 

No comments:

Post a Comment