Jesin's Blog

Welcome to the Portal of Technology

  • Facebook
  • GitHub
  • RSS
  • Twitter
  • Home
  • Categories
    • Domains
    • Linux
    • Networking
    • PHP
    • Virtualization
    • Web Design
    • Web Servers
    • Windows
  • WordPress Plugins
    • Custom Error Pages
    • HTTP Digest Authentication
    • Mailgun Email Validator
  • Toolbox
    • DNS Lookup Tool
    • htdigest Generator Tool Online
    • htpasswd Generator Tool Online
    • HTTP Headers Lookup Tool
    • MD5 Encryption Tool
    • Open Port Check Tool
    • SHA-1 Encryption Tool
    • URL Encoding/Decoding Tool
  • About Me
  • Contact Me
  • Sitemap
Home ›
PHP ›
Connect PHP with MySQL

Connect PHP with MySQL

November 26, 2010 PHP Jesin A 1 Comment

connect php with mysql thumbnail

Connect PHP with MySQL database, execute queries to manipulate information and retrieve data and display it using MySQL. Connecting with a MySQL database using PHP requires the use of three functions mysql_connect() mysql_select_db() and mysql_query() In this article I’ll be explaining how to connect to a MySQL server, create a database, create a table, insert values into it and retrieve it to display it in the form of HTML tables.Warning:- Some example source code might contain a die(mysql_error()) statement, if you are planning to use your web application in a production environment please REMOVE that statement from the code after development and debugging is over. It might expose your database credentials.

PHP connect to a MySQL server

The first objective is to connect to a MySQL server. So use the mysql_connect() function. The syntax is

mysql_connect("MySQL Host","Username","Password");

In most situations the MySQL host is localhost, if there is no password for your server (which is the case if you’re using WAMP or XAMPP) just use two empty double quotes WITHOUT any space in between them. You might want to use a die() function to display MySQL errors if any

mysql_connect("MySQL Host","Username","Password") or die(mysql_error());

Create a MySQL database

The second step is to create a MySQL database using PHP. In this step the mysql_query() function will be used to execute the query to create a database. So this function will be used along with the mysql_connect() function

mysql_connect("MySQL Host","Username","Password");
mysql_query("CREATE DATABASE database_name");

Now if you run this script you’ll be presented with a blank page so lets use if else statement to check whether the operation was successful

mysql_connect("MySQL Host","Username","Password");
$create_db = mysql_query("CREATE DATABASE database_name");
if ($create_db)
print "database was successfully created";
else
print mysql_error();
mysql_close();

If the database was created you see the message inside the if loop, if you refresh the page once again you’ll see an error message “Can’t create database ‘database_name’; database exists”

Connect to the MySQL database

Do not confuse with the term connect, the mysql_connect() function connects to MySQL server but to establish a connection with a database the mysql_select_db() function is used. Add the function along with mysql_connect() function

mysql_connect("MySQL Host","Username","Password");
$selectdb = mysql_select_db("database_name");
if ($selectdb)
print "Connection was successful";
else
print mysql_error();
mysql_close();

This will display a message to show whether connection was established correctly.

Create a Table

After creating a database it is now time to create a table. Creating a table is just a matter of executing SQL queries using the mysql_query(). For this example I’ll be creating a table containing fields(columns) employee name and employee id.

mysql_connect("MySQL Host","Username","Password");
mysql_select_db("database_name");
$create_table = mysql_query("CREATE TABLE employees (employee_name VARCHAR(30) NOT NULL, employee_id int(6) NOT NULL, PRIMARY KEY (employee_id))");
if($create_table)
print "Table was successfully created";
else
print mysql_error();
mysql_close();

If the table was successfully created you’ll see a confirmation else you’ll get a error message. Here PRIMARY KEY is used to ensure no identical employee Ids are inserted.

Insert data into the table

After creating a table records need to be added so the insert query will be used tinside the mysql_query() function. The HTML input form I’m using will have the text box names as eid and ename for employee ID and employee name respectively.

$id=stripslashes(trim($_POST['eid']));
$employee=stripslashes(trim($_POST['ename']));
mysql_connect("MySQL Host","Username","Password");
mysql_select_db("database_name");
$add=mysql_query("INSERT INTO employees(employee_id,employee_name) values('$id','$employee')");
if($add)
print "User successfully added";
else
print mysql_error();
mysql_close();

If you’re wondering what the two new functions stripslashes() and trim() are for, they are there to prevent SQL injection attacks. The stripslashes() function removes any quote characters entered in the text box and the trim() function removes whitespace from the starting and end of the string.

Retrieve data from the table

The final operation would be to display the data in the table in an user friendly format. Lets use the select query for this purpose.

mysql_connect("MySQL Host","Username","Password");
mysql_select_db("database_name");
$data=mysql_query("SELECT * FROM employees");
print "
<table>
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
</tr>";
while($value=mysql_fetch_array($data))
{
print "
<tr>
<td>".$value['employee_id']."</td>
<td>".$value['employee_name']."</td>
</tr>";
}
print "</table>";
mysql_close();

The function mysql_fetch_array() will return a multidimensional array containing values from the select query. The values are displayed using a HTML table in the front-end.

Related posts:

php category thumbnailCreating a PHP MySQL Login Page Script web design category thumbnailUsername availability check with AJAX and PHP php category thumbnailPHP Pie Chart Script php category thumbnailHow to reset the Joomla Administrator password forgot mysql password windows smileyResetting MySQL root password in Windows

Tags: mysql, php

Trackbacks

  1. Username availability check with AJAX and PHP | Jesin's Blog says:
    March 13, 2013 at 8:49 pm

    […] be concentrating more on the AJAX part and less on PHP because I have already written an article on how to connect PHP and MySQL. In the end of this article there is a link to a demo which I created, it has a HTML form sans form […]

    Reply

Leave a Reply Cancel reply

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

Get a wealth of information delivered to your inbox. Subscribe and never miss a single article.

  • Tutorials and howtos
  • Code, scripts and commands
  • Online Tools

* No spam, unsubscribe anytime

Hire Me

  • SSL installation and hardening (A+ on Qualys SSL test)
  • Apache & Nginx configuration
  • Email deliverability improvement (10/10 on Mail Tester & MailGenius)
  • WordPress customization, optimization and migration
  • and much more…

    Tools

    • DNS Lookup Tool
    • htdigest Generator Tool Online
    • htpasswd Generator Tool Online
    • HTTP Headers Lookup Tool
    • MD5 Encryption Tool
    • Open Port Check Tool
    • SHA-1 Encryption Tool
    • URL Encoding/Decoding Tool

    Nav

    • Home
    • About Me
    • Contact Me
    • Privacy Policy
    • Sitemap
    Vultr SSD VPS

    Creative Commons License
    Jesin's Blog by Jesin A is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
    Based on a work at websistent.com.