CENT CI CENT CI - 1 year ago 86
MySQL Question

I tried to connect to xampp database but its failing

I am trying so hard to connect to the database but am failing, am using xampp with php 7.0.8, am confused i dont know how i should access my database.
Can someone help me please?

Here is my code:

mysql_connect("localhost", "root", "") or die (mysql_error ());

Answer Source

first of all you should mysqli_ instead of mysql_ cause mysql_ is deprecated since php 5.5.0.

for connect to any database there are 3 options you can handle it with php.

MySQLi Object-Oriented

$servername = "localhost"; //the host
$username = "username"; // the db_username
$password = "password"; //the db_paswword
$dbname = "dbanme"; //your databasename

// do a new connection here
$conn = new mysqli($servername, $username, $password);

// echeck here for errors
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
echo "Connected successfully";

MySQLi Procedural

$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
echo "Connected successfully";


$servername = "localhost";
$username = "username";
$password = "password";

try {
    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    // set the PDO error mode to exception
    echo "Connected successfully";
catch(PDOException $e)
    echo "Connection failed: " . $e->getMessage();

and at least you have to close the connection with this 3 parameters:

  1. For MySQLi Object-Oriented it is : $conn->close();
  2. For MySQLi Procedural it is : mysqli_close($conn);
  3. For PDO it is : $conn = null;

so what should you use now for the best ?

Both MySQLi and PDO have their advantages:

PDO will work on 12 different database systems, where as MySQLi will only work with MySQL databases.

So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the entire code - queries included.

Both are object-oriented, but MySQLi also offers a procedural API.

Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download