PHP/MySQL Database/mysqli connect
Содержание
- 1 custom-error-messages.php
- 2 Discovering Which Extension Is Being Used
- 3 function mysql_connect() establishes an initial connection with the MySQL server.
- 4 In PHP 5 using the MySQLi extension
- 5 MySQL Connection Test
- 6 <?php $connection = mysql_connect( "localhost", "root", "" ) or die( "Sorry - unable to connect to MySQL" ); echo( "Congratulations - you connected to MySQL" ); ?>
custom-error-messages.php
<source lang="html4strict">
$errors = array (
"1045" => "Unable to authenticate user.", "2005" => "Unable to contact the MySQL server.", "2013" => "Lost MySQL connection." );
$link = @mysqli_connect("127.0.0.1", "root","", "mydatabase"); if (!$link) {
$errornum = mysqli_connect_errorno(); echo $errors[$errornum];
}
</source>
Discovering Which Extension Is Being Used
<source lang="html4strict">
<?php
function mysqlinstalled (){ if (function_exists ("mysql_connect")){ return true; } else { return false; } } function mysqliinstalled (){ if (function_exists ("mysqli_connect")){ return true; } else { return false; } } if (mysqlinstalled()){echo "
The mysql extension is installed.
";} else {echo "
The mysql extension is not installed..
";} if (mysqliinstalled()){echo "
The mysqli extension is installed.
";} else {echo "
The mysqli extension is not installed..
";}
?>
</source>
function mysql_connect() establishes an initial connection with the MySQL server.
<source lang="html4strict">
int mysql_connect([string hostname [:port] [:/path/to/socket] [, string username][, string password])
<? @mysql_connect("localhost", "web", "aaaa") or die("Could not connect to MySQLserver!"); ?> In this case, localhost is the server host, web is the username, and aaaa is the password. The @ will suppress any error message that results from a failed attempt.
</source>
In PHP 5 using the MySQLi extension
<source lang="html4strict">
<?php
$mysqli = mysqli_connect("localhost", "root", "","mydatabase", 3306); $result = mysqli_query($mysqli, "SELECT * FROM mytable"); while($row = mysqli_fetch_array($result)) { foreach($row as $key => $value) { echo "$key = $value</BR>\n"; } } mysqli_free_result($result); mysqli_close($mysqli);
?>
</source>
MySQL Connection Test
<source lang="html4strict">
<html>
<head> <title>MySQL Connection Test</title> </head> <body>
<?php $connection = mysql_connect( "localhost", "root", "" ) or die( "Sorry - unable to connect to MySQL" ); echo( "Congratulations - you connected to MySQL" ); ?>
</body>
</html>
</source>