php连接mysql数据库
步骤
- 连接数据库
$link = mysqli_connect('localhost','root','123456');
- 判断/返回连接状态
if(!$link){
echo "不儿,tm卧槽~数据库连接失败";
}
- 设置连接字符集
mysqli_set_charset($link,'utf8')
- 选择数据库
mysqli_select_db($link,'warmwinterI')
- 准备sql语句
$sql = "select * from mycoachinfo"
- 发送sql语句
$res = mysqli_query($link,$sql)
- 处理结果集
$result = mysqli_fetch_assoc($res)//返回值是关联数组,执行一次,往下读一行
var_dump($result)
- 关闭数据库释放资源
mysqli_close($link)
综合演练
<?php
$link = mysqli_connect('127.0.0.1','root','wenwajiao'); //注意,主机域名务必写为127.0.0.1如果是localhost肯定会出幺蛾子!!!
if ($link)
{
mysqli_set_charset($link,'utf8');
mysqli_select_db($link,"oldpassion");
$sql = "select * from loginfo";
$res = mysqli_query($link,$sql);
while($rows = mysqli_fetch_assoc($res)){
var_dump($rows);
echo "<br/>";
}
};
$sql2 = "select * from loginfo";
$res = mysqli_query($link,$sql2);
$count= mysqli_num_rows($res);
echo $count."<br/>";
echo "上面是关联数组"."<br/>";
echo "==============================="."<br/>";
echo "下面是索引关联数组"."<br/>";
while($workout = mysqli_fetch_array($res))
{
var_dump($workout);
echo "<br/>";
}
?>
- mysqli_num_rows//返回查询的行数
- mysqli_fetch_array//返回一个既有索引又有关联的数组
- mysqli_affected_rows//返回删除,修改等操作受影响的行数
<?php $link=mysqli_connect('127.0.0.1','root','wenwajiao'); if ($link) { mysqli_set_charset($link,'utf8'); mysqli_select_db($link,'oldpassion'); $sql2 = "insert into loginfo values(4, 'xxd','徐晓冬','xxd')"; $res = mysqli_query($link,$sql2); $duwa = mysqli_affected_rows($link); echo $duwa."<br/>"; } ?>
- mysqli_insert_id//返回自增主键的值
<?php
$link=mysqli_connect('127.0.0.1','root','wenwajiao');
if ($link)
{
mysqli_set_charset($link,'utf8');
mysqli_select_db($link,'oldpassion');
$id = mysqli_insert_id($link);
echo $id;
$sql2 = "insert into loginfo values(4, 'xxd','徐晓冬','xxd')";
echo mysqli_insert_id($link)."<br/>";
$res = mysqli_query($link,$sql2);
$duwa = mysqli_affected_rows($link);
echo $duwa."<br/>";
}
?>