Firefog Firefog - 5 months ago 13
MySQL Question

How to connect MySQL db using new XAMPP

Old connection method

mysql_connect
maybe deprecated from PHP7 so what is the best way to connect and query in mysql using XAMPP or how I implement PDO in my bellow script.

<?php
$key = $_GET['key'];
$array = array();
$con = mysql_connect("localhost", "root", "");
$db = mysql_select_db("search", $con);

$query = mysql_query("select * from ajax_example where name LIKE '%{$key}%'");

while ($row = mysql_fetch_assoc($query)) {
$array[] = $row['name'];
}
echo json_encode($array);
?>

Apb Apb
Answer

Database connection using mysqli_* :

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";

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

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

For further mysqli_* statement syntax refer: Mysqli_* Manual

Database connection using PDO_* :

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";

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

For further PDO_* statement syntax refer PDO_* Manual

Comments