简体   繁体   中英

how to provide information from a mysql database on a website using php

I have a problem with providing infromation from a mysql database through php. I am working with brackets and always when I try to connect with my database (opening my connection, giving information about my server, port and the name of the dtabase -> shown in the code below) nothing happens. I can not administrate my database with phpmyadmin I know that would be easy. I also have xamp and a apache server working, but then I would have to use phpmyadmin to connect.

But is there a way to connect the database (created with mysql workbench running on localhost 127.0.0.1 and port 3306) only like that with my php file. Or is the problem that I have a mistake in my code?

Code:

File one: db_connection.php

<!DOCTYPE html>

<html>

    <header>

        <center> <h1>My New Website </h1> </center>

    </header>

    <body>

    <?php
        //die echo Funktion, ist dafür da, dass etwas in den Browser ausgegeben wird (same as Syso)
        //echo "Hello World!";

        function OpenConnection()
        {
            $dbhost = "localhost";
            $dbuser = "root";
            $dbpassword = "";
            $dbname = "dml_final";

            $connection = new mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname)
            or die ("Connection failed: %s\n". $connection -> error);

            return connection;
        }

        function CloseConnection()
        {
            $connection -> close();
        }

    ?>

    </body>

</html>

File two: index.php

<?php requires 'db_connection.php'; ?>
<!DOCTYPE html>

<html>

    <header>

        <center> <h1>My New Website </h1> </center>

    </header>

    <body>

    <?php

    $connection = openConnection();

    echo "Connection successfully!";

    CloseConnection($connection);

    ?>

    </body>

</html>

If you want to use your current way, change function to public function so that it is globally available across your website, I recommend the following method instead:

 $dbhost = "localhost";
 $dbuser = "root";
 $dbpassword = "";
 $dbname = "dml_final";

 $connection = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);

 if(!$connection) {
  die("Connection failed:".mysqli_connect_error());
 }

And you include this in all of your PHP files. To close the connection, simply run a mysqli_close($connection); . I don't know about you, but I find this way more simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM