PHP连接mysql数据库
PHP连接MySql 非常简单
但必须注意编码问题 编码不正确将会导致乱码问题
连接数据库代码如下:
代码
<?php
$link=mysql_connect("localhost","root","123")
or die("connect to database failed");
$result=mysql_query("create database trampt")
or die("query failed");
mysql_select_db("trampt");
mysql_query("set names UTF8");
$result=mysql_query("create table Users(userid int auto_increment primary key,username varchar(50),password varchar(50))")
or die("query failed");
mysql_query("insert into users(username,password) values('博客园','123')")
or die("insert record failed");
mysql_close($link);
?>
$link=mysql_connect("localhost","root","123")
or die("connect to database failed");
$result=mysql_query("create database trampt")
or die("query failed");
mysql_select_db("trampt");
mysql_query("set names UTF8");
$result=mysql_query("create table Users(userid int auto_increment primary key,username varchar(50),password varchar(50))")
or die("query failed");
mysql_query("insert into users(username,password) values('博客园','123')")
or die("insert record failed");
mysql_close($link);
?>
读取数据库代码如下:
<?php
require("inc/conn.php");
$result=mysql_query("select * from users");
while($ob=mysql_fetch_object($result))
{
echo "user name is : ".$ob->username."<br/>";
}
mysql_close($link);
?>
require("inc/conn.php");
$result=mysql_query("select * from users");
while($ob=mysql_fetch_object($result))
{
echo "user name is : ".$ob->username."<br/>";
}
mysql_close($link);
?>
注意编码问题的设置: 1 数据库设置utf-8的编码 2 页面编码设置为utf-8 3使用mysql_query("set names UTF8")
这样就避免了乱码问题