PHP/MySQL Database/mysqli connect
Содержание
custom-error-messages.php
$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];
}
Discovering Which Extension Is Being Used
<?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 "<p>The mysql extension is installed.</p>";
} else {
echo "<p>The mysql extension is not installed..</p>";
}
if (mysqliinstalled()){
echo "<p>The mysqli extension is installed.</p>";
} else {
echo "<p>The mysqli extension is not installed..</p>";
}
?>
function mysql_connect() establishes an initial connection with the MySQL server.
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.
In PHP 5 using the MySQLi extension
<?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);
?>
MySQL Connection Test
<html>
<head>
<title>MySQL Connection Test</title>
</head>
<body>
<h2>
<?php $connection = mysql_connect( "localhost", "root", "" )
or die( "Sorry - unable to connect to MySQL" );
echo( "Congratulations - you connected to MySQL" );
?>
</h2>
</body>
</html>