I tried to connect to xampp database but its failing

时间:2016-11-09 08:27:26

标签: php mysql html5

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

2 个答案:

答案 0 :(得分:2)

您需要使用mysqli代替mysql。因为mysql扩展现在是deprecated。 以下是syntax的{​​{1}}:

mysqli

答案 1 :(得分:1)

首先,您应该{php = {1}}而不是mysqli_,因为自PHP 5.5.0以来已弃用mysql_

对于连接到任何数据库,有3个选项可以用php处理它。

MySQLi面向对象

mysql_


MySQLi程序

<?php
$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";
?> 


PDO

<?php
$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";
?> 

至少你必须用这3个参数关闭连接

  1. 对于MySQLi面向对象,它是:<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $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(); } ?>
  2. 对于MySQLi程序,它是:$conn->close();
  3. 对于PDO,它是:mysqli_close($conn);

  4. 那么你现在应该用什么来做到最好?

    MySQLi和PDO都有其优势:

    PDO将在12个不同的数据库系统上运行,而MySQLi 可以使用MySQL数据库。

    因此,如果您必须将项目切换为使用其他数据库, PDO会使流程变得轻松。您只需要更改连接字符串和一些查询。使用MySQLi ,您需要重写整个代码 - 包含查询。

    两者都是面向对象的,但MySQLi也提供了程序API。

    两者都支持准备好的陈述。准备好的语句可以防止SQL注入,对Web应用程序的安全性非常重要。