Home  >  Article  >  Database  >  Simple sample code for connecting to mysql database

Simple sample code for connecting to mysql database

怪我咯
怪我咯Original
2017-07-11 15:43:142062browse

Once you get a connection to the MySQL server, you need to choose a specific database to work with. This is because the MySQL server may have more than one database.

From the command prompt, select MySQL Database :

It is very simple to select a specific database mysql> prompt . To select a specific database, you can use SQL commands.
Example:

The following is an example, selecting the database called TUTORIALS:

[root@host]# mysql -u root -p
Enter password:******
mysql> use TUTORIALS;
Database changed
mysql>

Now the tutorial database has been selected and all subsequent operations will be carried out.

Note: All database names, table names, and field names in tables are case-sensitive. So will have to use prpoer name while giving any SQL command.
Use a PHP script to select a MySQL database:

PHP provides the function mysql_select_db to select a database. Returns TRUE on success, FALSE otherwise.
Syntax:

bool mysql_select_db( db_name, connection );

Example:

The following is an example showing how to select a database.

<html>
<head>
<title>Selecting MySQL Database - by www.jb51.com</title>
</head>
<body>
<?php
$dbhost = &#39;localhost:3036&#39;;
$dbuser = &#39;guest&#39;;
$dbpass = &#39;guest123&#39;;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
 die(&#39;Could not connect: &#39; . mysql_error());
}
echo &#39;Connected successfully&#39;;
mysql_select_db( &#39;TUTORIALS&#39; );
mysql_close($conn);
?>
</body>
</html>

The above is the detailed content of Simple sample code for connecting to mysql database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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