mysql_connect在将来的php版本会被废弃,建议用mysqli或者PDO代替
通过php添加数据
/*
mysql> create table people(
-> id int unsigned primary key auto_increment,
-> name varchar(20),
-> age int
-> );
*/
header("Content-type:text/html;charset=utf-8");
//连接数据库
$link = mysql_connect("localhost","root","123456");
//选择数据库
mysql_select_db("t2");
//设置字符集(client字符集和conn.字符集);
mysql_query("set names utf8");
$name = "user4";
$age = "213";
//sql语句
$sqlSelect = "insert into people(name,age) values('{$name}','{$age}'),('{$name}','{$age}')";
//执行sql语句
$result = mysql_query($sqlSelect);
if($result){
echo '添加影响多少行:'.mysql_affected_rows();
}else{
echo '添加失败';
}
//mysql_free_result仅需要在考虑到返回很大的结果集时会占用多少内存时调用。在脚本结束后所有关联的内存都会被自动释放。
//mysql_free_result($result);
//关闭数据库
mysql_close($link);
通过php删除数据
header("Content-type:text/html;charset=utf-8");
//连接数据库
$link = mysql_connect("localhost","root","123456");
//选择数据库
mysql_select_db("t2");
//设置字符集(client字符集和conn.字符集);
mysql_query("set names utf8");
//sql语句
$sqlSelect = "delete from people where id>5";
//执行sql语句
$result = mysql_query($sqlSelect);
if($result){
echo '查询影响多少行:'.mysql_affected_rows();
}else{
echo '删除失败';
}
mysql_close($link);
通过php更新数据
header("Content-type:text/html;charset=utf-8");
//连接数据库
$link = mysql_connect("localhost","root","123456");
//选择数据库
mysql_select_db("t2");
//设置字符集(client字符集和conn.字符集);
mysql_query("set names utf8");
//sql语句
$sqlSelect = "update people set name='linei2' where id=61";
//执行sql语句
$result = mysql_query($sqlSelect);
if($result){
echo '更新影响多少行:'.mysql_affected_rows();
}else{
echo '更新失败';
}
mysql_close($link);
通过php查找数据
header("Content-type:text/html;charset=utf-8");
//连接数据库
$link = mysql_connect("localhost","root","123456");
//选择数据库
mysql_select_db("t2");
//设置字符集(client字符集和conn.字符集);
mysql_query("set names utf8");
//sql语句
$sqlSelect = "select * from people";
//执行sql语句
$result = mysql_query($sqlSelect);
while ($row = mysql_fetch_assoc($result)){
echo "{$row['id']}".' --- '."{$row['name']}".' -- '."{$row['age']}".'<br/>';
}
echo '查询到的行数:'.mysql_num_rows($result);
//mysql_free_result仅需要在考虑到返回很大的结果集时会占用多少内存时调用。在脚本结束后所有关联的内存都会被自动释放。
mysql_free_result($result);
mysql_close($link);