如何使用新的XAMPP连接MySQL数据库

时间:2016-06-06 07:14:53

标签: php mysql

旧的连接方法mysql_connect可能已经从PHP7中弃用了,所以使用XAMPP在mysql中连接和查询的最佳方式是什么,或者我如何在我的下方脚本中实现PDO。

<?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);
?>

2 个答案:

答案 0 :(得分:3)

使用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";
?>

有关mysqli_*语句的更多语法,请参阅:Mysqli_* Manual

使用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();
}
?>

对于进一步的PDO_*语句语法,请参阅PDO_* Manual

答案 1 :(得分:-1)

    $conn = new Connection(); 
    $query = "select * from ajax_example where name LIKE '%{$key}%'";
    $res = $conn->execute_query($query)->fetchall(PDO::FETCH_ASSOC);
    if (!empty($res)) 
    {    
        $result['data'] = $res;
        echo json_encode($result);
    }