方式一:已经过时
1.造一个连接(建立通道)
$db = mysql_connect("localhost","root","123");
2.选择要操作哪一个数据库
mysql_select_db("mydb",$db);
3.写SQL语句
$sql = "select * from Info";
4.执行SQL语句,返回结果集
$result = mysql_query($sql);
5.从结果集中取数据
while($row = mysql_fetch_row($result))
{
var_dump($row);
}
方式二:面向对象的方式
1.造一个连接对象
$db = new MySQLi("localhost","root","123","mydb");
2.判断连接是否出错
if(mysqli_connect_error())
{
echo "连接失败";
exit(); //退出程序
}
!mysqli_connect_error() or die("连接失败!");
3.写SQL语句
$sql = "select count(*) from Info";
$sql = "insert into Info values(‘p001‘,‘‘,‘‘,‘‘,‘‘)";
4.执行SQL语句,查询语句如果执行成功返回结果集对象,如果执行失败返回false
$result = $db->query($sql);
5.从结果集中读取数据
if($result)
{
var_dump($result->fetch_row()); //返回一行数据的数组(索引数组)
while($row = $result->fetch_row())
{
var_dump($row);
}
var_dump($result->fetch_assoc());//返回一行数据(关联数组)
$shuju = $result->fetch_all();//返回所有数据(二维数组)
var_dump($result->fetch_object());//返回一行数据(对象)
echo $shuju[0][0];
}
1.造连接对象
$db = new MySQLi("localhost","root","123","mydb");
2.判断是否出错
!mysqli_connect_error() or die("连接失败!");
3.写SQL语句
$sql = "select * from Nation";
4.执行SQL语句
$result = $db->query($sql);
5.取数据
if($result)
{
$attr = $result->fetch_all();
echo "<select>";
foreach($attr as $v)
{
echo "<option value=‘{$v[0]}‘>{$v[1]}</option>";
}
echo "</select>";
}
?>