Connecting to and running queries on MySQL from PHP using mysql and mysqli extensions

MySQL is the common database used by utmost web developers. There are two ways in which one can connect to a MySQL database and execute query in PHP.

View Source

Technique 1 : The traditional way

This is outdated and should not be used in real time because it has many security issues. Just kept here for reference.

 

<?php $con = mysql_connect($db_host, $db_username, $db_password);  if ($con) {     $selDb = mysql_select_db($db_database, $con);     if(!$selDb)     {         die("Unable to select database : ".mysql_error());     } } else {     die('Could not connect: ' . mysql_error()); } $sql="Your Query Here"; mysql_query($sql);

 

Technique 2: The advanced and improved MySQLi

Here i in the MySQLi stands for improved.

There are two sub techniques in using the MySQLi extension.

1. Procedural:

<?php $con=mysqli_connect($db_host, $db_username, $db_password,$db_database); if (mysqli_connect_errno()) {     echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql="Your Query Here"; mysqli_query($con,$sql);

 

2. Object Oriented:
We here at A M Reddy’s prefer this method

<?php $con=new mysqli($db_host, $db_username, $db_password,$db_database); if ($con->connect_error) {       die('Connect Error (' . $con->connect_errno . ') '. $con->connect_error); } $sql="Your query here"; $data=$con->query($sql);

 

Best way to keep yourself away from any chances of SQL injection is by using parameterized queries which allows you to define the type of input you give as a variable in string and so this makes it difficult for SQL injection.

Leave a Reply

Your email address will not be published.