PHP/MySQL Database/mysql connect
Содержание
A function to open a connection to mysql
<?php
function opendatabase ($host,$user,$pass) {
try {
if ($db = mysql_connect ($host,$user,$pass)){
return $db;
} else {
throw new exception ("Sorry, could not connect to mysql.");
}
} catch (exception $e) {
echo $e->getmessage ();
}
}
function closedatabase ($db){
mysql_close ($db);
}
$db = opendatabase ("localhost","root","");
try {
if (!mysql_select_db ("mydatabase",$db)){
throw new exception ("Sorry, database could not be opened.");
}
$myquery = "INSERT INTO mytable (id,title,myvalue) VALUES (0,"Blue",20)";
if (mysql_query ($myquery, $db)){
echo "We were successful.";
} else {
throw new exception (mysql_error());
}
} catch (exception $e) {
echo $e->getmessage();
}
closedatabase ($db);
?>
Connecting to a MySQL Database
resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]] )
<?php
try {
$mysqlhost = "localhost";
$mysqluser = "root";
$mysqlpass = "";
if ($db = mysql_connect ($mysqlhost,$mysqluser,$mysqlpass)){
echo "Successfully connected to the database.";
mysql_close ($db);
} else {
throw new exception ("Sorry, could not connect to mysql.");
}
} catch (exception $e) {
echo $e->getmessage ();
}
?>
Connecting user
<?php
$domain = "localhost";
$user = "userName";
$password = "password";
$conn = mysql_connect( $domain, $user, $password );
if($conn)
{
$msg = "Congratulations $user, You connected to MySQL";
}
?>
<html>
<head>
<title>Connecting user</title>
</head>
<body>
<h3>
<?php echo( $msg ); ?>
</h3>
</body>
</html>
Creating databases
<?php
$conn = @mysql_connect( "localhost", "userName", "password" )
or die( "Sorry - could not connect to MySQL" );
$rs1 = @mysql_create_db( $_REQUEST["db"] );
$rs2= @mysql_list_dbs($conn);
$list = "";
for( $row=0; $row < mysql_num_rows( $rs2 ); $row++ )
{
$list .= mysql_tablename( $rs2, $row ) . " | ";
}
?>
<html>
<head>
<title>Creating databases</title>
</head>
<body>
<form action="<?php echo( $_SERVER["PHP_SELF"] ); ?> " method="post">
Current databases: <?php echo( $list ); ?>
<hr>
Name:<input type = "text" name = "db">
<input type = "submit" value = "Create database">
</form>
</body>
</html>
When connecting to multiple MySQL servers, a link ID must be generated.
For example:
<?
$link1 = @mysql_connect("www.somehost.ru", "web", "abcde") or die("Could not connect to MySQL server!");
$link2 = @mysql_connect("www.someotherhost.ru", "usr", "secret") or die("Could not connect to MySQL server!");
?>