MYSQL入門之二_PHP操作MYSQL 1. 本地連接MySQL www.2cto.com $con= mysql_connect("localhost", "root", "xxxxxx"); if(!$con) { die('Could not connect: ' .mysql_error()); }else { echo"Connect success <br/>\n"; } 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 <br/>\n"; } 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<br/>\n"; }else { echo"Error creating database: " . mysql_error() ."<br/>\n"; } 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<br/>\n"; }else { echo"Error creating table: " . mysql_error() . "<br/>\n"; } 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"<br/>"; } 8. 設置字符集(設置之後的sql操作基於utf8字符集) mysql_query("SET NAMES 'utf8'"); mysql_query("SET CHARACTER_SET_CLIENT=utf8"); mysql_query("SET CHARACTER_SET_RESULTS=utf8");