Home > Article > Backend Development > How to use pdo to close the database in php
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)].
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['PHP_SELF']));?>"> 服务器地址:<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['REQUEST_METHOD']=="POST"){//if判断是否POST提交 $servername=$_POST['mysqlPDOip']; $username=$_POST['mysqlPDOuser']; $password=$_POST['mysqlPDOpassword']; 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(); } } ?>
Output:
try { //...} catch(Exception $e) { //...}
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!