MYSQL 入门之二 _PHP 操作 MYSQL

1. 本地连接 MySQL

** $con= mysql_connect("localhost", "root", "xxxxxx"); **

** if(!$con) { **

** die('Could not connect: '.mysql_error()); **

** }else { **

** echo"Connect success
"; **

** } **

2. SAE 连接 MySQL

** $con =mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT, **

** SAE_MYSQL_USER,SAE_MYSQL_PASS); **

** if (!$con) { **

** die('Could not connect: '.mysql_error()); **

** } else { **

** echo"Connect success
"; **

** } **

** mysql_select_db(SAE_MYSQL_DB,$con); **

3. 断开 MySQL

** mysql_close($con); **

4. 建立数据库

** $sql = "CREATE DATABASE IFNOT EXISTS $DATABASE_NAME"; **

** if(mysql_query($sql, $con)) { **

** echo "Database create success
"; **

** }else { **

** echo"Error creating database: ". mysql_error()."
"; **

** } **

5. 连接使用数据库

** mysql_select_db(\(DATABASE_NAME,\)con); **

6. 建立数据表

** $sql ="CREATE TABLE $TABLE_NAME (**

** namevarchar(80), **

** ageint **

)ENGINE=MyISAM DEFAULT CHARSET=utf8";

** if(mysql_query(\(sql,\)con)) { **

** echo "Table create success
"; **

** }else { **

** echo"Error creating table: ". mysql_error(). "
"; **

** } **

7. 查找数据

** $sql= "SELECT * FROM \(TABLE_NAME where name like \"%\)INPUT%""; **

** \(result= mysql_query(\)sql,$con); **

** while(\(row =mysql_fetch_array(\)result)) { **

** echo$row['name']. " ". $row['age']; **

** echo"
"; **

** } **

8. 设置字符集(设置之后的 sql 操作基于 utf8 字符集) ** mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER_SET_CLIENT=utf8");
mysql_query("SET CHARACTER_SET_RESULTS=utf8"); **