Home > Backend Development > PHP Problem > How to use pdo to close the database in php

How to use pdo to close the database in php

王林
Release: 2023-03-06 07:34:02
Original
2346 people have browsed it

php uses pdo method to close the database: [$conn = null;]. If you want to connect to the database, the method is [$conn = new PDO("mysql:host=$server;dbname=mysql", $user, $password)].

How to use pdo to close the database in php

Implementation code:

(Recommended tutorial: php video tutorial)

<meta http-equiv="content-type" content="text/html" charset="utf-8"/>
<form method="POST" action="<?php echo iconv("GB2312","UTF-8",htmlspecialchars($_SERVER[&#39;PHP_SELF&#39;]));?>">
服务器地址:<input type="text" name="mysqlPDOip"/><br/>
服务器账号:<input type="text" name="mysqlPDOuser"/><br/>
服务器密码:<input type="password" name="mysqlPDOpassword"/><br/>
<input type="submit" value="连接mysql"/>
</form>
<?php
if($_SERVER[&#39;REQUEST_METHOD&#39;]=="POST"){//if判断是否POST提交
    $servername=$_POST[&#39;mysqlPDOip&#39;];
    $username=$_POST[&#39;mysqlPDOuser&#39;];
    $password=$_POST[&#39;mysqlPDOpassword&#39;];
    try{
        //$conn = new PDO("mysql:host=$servername;dbname=myDB",$username,$password);
        $conn = new PDO("mysql:host=$servername;dbname=mysql", $username, $password);//连接数据库
        echo "连接成功!";
        echo "<br/>你所连接的服务器地址:".$servername;
        echo "<br/>你所连接的服务器账号:".$username;
        echo "<br/>你所链接的服务器密码:".$password;
        $conn = null;//关闭数据库连接
        echo "<br/>已成功关闭数据库";
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}
?>
Copy after login

Output:

How to use pdo to close the database in php

try
{ //...}
catch(Exception $e)
{ //...}
Copy after login

try{}catch{} in PHP is exception handling

Put the code to be executed into the TRY block. If there is a problem during the execution of these codes, If an exception occurs in a statement, the program jumps directly to the CATCH block, and $e collects error information and displays it.

If an exception is thrown, the script in the try statement will stop executing and then immediately redirect Execute the script in the catch statement.

If an exception is thrown but is not caught, a fatal error will be generated.

Related recommendations: php training

The above is the detailed content of How to use pdo to close the database in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template