一:链接数据库:
$mysqli=@new mysqli("localhost","root","123456","msqldb");
二:判断链接是否成功:
if(mysqli_connect_errno()){ echo "连接数据库失败:".mysqli_connect_error; $mysqli=null; exit; }
三:拼接SQL语句
$sql="";
四:执行SQL语句
$result=$mysqli->query($sql);
五:处理结果集:
1.非select
a.获取自动增长的行数:
$mysql->insert_id(); //insert into (只有在有自动增长的表中使用)
b.获取影响的行数:
$mysql->affected_rows();//可以判断记录是否改变,改变有值,不改变没有值
2.(select)
1.$result->fetch_row() mysql->fetch_row(); //返回索引数组 2.$result->fetch_assoc() mysql->fetch_assoc(); //返回关联数组 3.$result->fetch_array() mysql->fetch_array(); //返回索引和关联两个数组 4.$result->fetch_object() mysql->fetch_object(); //将一条记录以对象的形式返回
while($row=$result->fetch_assoc()){ $return_value[]=$row; } foreach($return_value as $row){ echo "<tr>"; echo "<td>{$row['id']}</td>"; echo "<td>{$row['cid']}</td>"; echo "<td>{$row['name']}</td>"; echo "<td>{$row['price']}</td>"; echo "<td>{$row['num']}</td>"; echo "<td>{$row['description']}</td>"; echo "</tr>"; }
执行SQL语句获取字段信息
field_count();获取结果集中的列数
field_rows(); 获取结果集中的行数
六:获取字段信息:
while($files=$result->fetch_field()){ echo "<th>"; echo $files->name; echo "</th>"; }
其它:
1.max_length 最大长度
2.current_lengths 当前列
七:$mysql->close();
mysqli一些常用的成员函数:
- mysqli::character_set_name — 返回当前数据库连接的默认字符编码
- mysqli::get_client_info — Get MySQL client info(获取客户机属性)
- mysqli::$host_info — Returns a string representing the type of connection used(返回服务器信息)
- mysqli::$server_info — Returns the version of the MySQL server(服务器配置)
- mysqli::$server_version — Returns the version of the MySQL server as an integer(服务器版本)