用SQL和PHP连接到数据库[关闭]

问题描述:

I'm making a website that uses SQL and PHP functionalities. How do I connect to a database?

我正在创建一个使用SQL和PHP功能的网站。 如何连接数据库? p> div>

The easiest way that I do with my site is make a file called db.php containing:

<?php
$host = 'localhost';
$user = 'root';
$pass = 'password';
$db = 'databasename';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);

..then in the index.php file, at the top:

<?php
require_once('db.php')
?>

I would advise you begin by looking here.

You need to ensure that you have created user credentials with the correct permissions to query the database before you try this. You can do this through the cPanel of your web server (I'm going to assume you are using a web hosted server for this question).

Once you have a working and tested connection to the database, you can then start looking at the mySQLi documentation here. Which will show you how to execute and retrieve results from a database query and how to handle the returned data with PHP.

I see you are seriously downvoted. I learned it the hard way and I am still learning to post here.

Stack sites are supposed to be searched first. If your question is already answered then people downvote you.

The solution to your question:

In your mysql or phpmyadmin you can set whether you use a password or not. The best way to learn is to set mysql with a password in my opinion. If you will launch a website online finally, you have to take security measures anyway.

If you make contact to your mysql database with you have to set: username, password, database and servername ( for instance localhost).

The most secure way is using the OOP / prepared method:

        $servername ='localhost';
        $username='yourname';
        $password='12345';
        $dbname='name_database';


        $conn = new mysqli($servername, $username, $password, $dbname);

        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }


        if ($stmt = $conn->prepare("SELECT idnum, col2, col FROM `your_table` WHERE idnum ='5'  ")) { 




            $stmt->execute();

            $res = $stmt->get_result();
            $qrow = mysqli_num_rows($res);


            while ($row = mysqli_fetch_assoc($res)) {

            var_dump($qrows); // number of rows you have
                $total = implode(" / " , $row);
        var_dump($total);

            $idnum = $row['idnum'];
            var_dump($idnum);

            }