php 如何使用新的 XAMPP 连接 MySQL 数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37651539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to connect MySQL db using new XAMPP
提问by Firefog
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.
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);
?>
回答by Apb
Database connection using mysqli_*
:
数据库连接使用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
有关进一步的mysqli_*
语句语法,请参阅:Mysqli_*
手册
Database connection using PDO_*
:
数据库连接使用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
有关进一步的PDO_*
语句语法,请参阅PDO_*
手册
回答by kiran gadhvi
$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);
}