时间:2021-07-01 10:21:17 帮助过:2人阅读
MYSQL入门之二_PHP操作MYSQL
1. 本地连接MySQL
$con= mysql_connect("localhost", "root", "xxxxxx");
if(!$con) {
die('Could not connect: ' .mysql_error());
}else {
echo"Connect success
/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
/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
/n";
}else {
echo"Error creating database: " . mysql_error() ."
/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
/n";
}else {
echo"Error creating table: " . mysql_error() . "
/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"
";
}
8. 设置字符集(设置之后的sql操作基于utf8字符集)
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER_SET_CLIENT=utf8");
mysql_query("SET CHARACTER_SET_RESULTS=utf8");
bitsCN.com