Abstract: 用PHP操作MySQL数据库

一、常用函数

函数名称 作用
mysql_connect(host, uname, passwd) 进行数据库连接
mysql_select_db(‘database’) 选择数据库
mysql_query(sql) 向数据库发送指令
mysql_fetch_array() 获取数据集中一行数据
mysql_fetch_row() 获取数字索引数组
mysql_fetch_assoc() 获取关联索引数组

二、循环遍历查询结果

1. while

sql.php

1
2
3
4
5
6
7
8
<?php 
$host = '127.0.0.1';
$username = 'root';
$password = 'root';
@$con = mysql_connect($host, $username, $password) or die(mysql_error());
mysql_select_db('test') or die(mysql_error());
mysql_query('set names "utf8"') or die(mysql_error());
?>
1
2
3
4
5
6
7
8
9
10
<?php
include 'sql.php';
$sql = "SELECT * FROM `content`;";
$result = mysql_query($sql);
while($arr = mysql_fetch_assoc($result)){
$title = $arr['title'];
$author = $arr['author'];
echo $author. '->' . $title;
}
?>

2. for

1
2
3
4
5
6
7
8
9
10
11
<?php
include 'sql.php';
$sql = "SELECT * FROM `content`;";
$result = mysql_query($sql);
for($i=0; $i<mysql_affected_rows(); $i++){
$arr = mysql_fetch_assoc($result);
$title = $arr['title'];
$author = $arr['author'];
echo $author. '->' . $title;
}
?>

三、对密码的处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
session_start();
//若$_SESSION['uname']为空则跳转到登录页面
if(!$_SESSION('uname')){
header("Location: login.php");
die();
}
@$old_pass = $_POST['old_pass'];
@$new_pass = $_POST['new_pass'];
@$new_pass_again = $_POST['new_pass_again'];
if($old_pass && $new_pass && $new_pass_again){
if($new_pass != $new_pass_again){
die("<script>alert('两次输入密码不一致,请重新输入!')</script>");
}
$pass = md5($new_pass);
$uid = $_SESSION['uid'];
include 'sql.php';
$sql = "UPDATE `users` SET `passwd` = '{$pass}' WHERE `id`={$uid};";
$result = mysql_query($sql) or die(mysql_error());

if(mysql_affected_rows()){
echo '<script>alert("密码修改成功!");</script>';
}else{
echo '<script>alert("密码修改成功!");</script>';
}
}
?>