牛骨文教育服务平台(让学习变的简单)
博文笔记

PHP连接MySQL进行查询操作

创建时间:2017-07-14 投稿人: 浏览次数:230

调用函数:

  1. mysql_fetch_row //索引数组
  2. mysql_fetch_assoc //关联数组
  3. mysql_fetch_array //混合数组
  4. mysql_fetch_object //对象

实例

mysql_fetch_row、mysql_fetch_assoc、mysql_fetch_array实现语句:

<?php

//通过PHP连接MySQL数据库
$connect=mysql_connect("localhost","root","998426");

//选择数据库
mysql_select_db("test");

//设置客户端字符集
mysql_query("set names utf8");

//通过PHP进行select操作
$sql="select * from user";

//执行MySQL语句
$result=mysql_query($sql);

//输出数据,用while循环,类似于c++中实现字符串串接的原型语句
while($row=mysql_fetch_row($result))
{
    echo "<pre>";
    print_r($row);
    echo "</pre>";
}

//释放结果集资源并关闭连接
mysql_close($sql);

结果:

Array
(
    [0] => 1
    [1] => user1
)

Array
(
    [0] => 3
    [1] => wang
)

Array
(
    [0] => 4
    [1] => user4
)

Array
(
    [0] => 5
    [1] => user5
)

mysql_fetch_object实现语句
注意:object的访问方式与c++中访问类的指针类似
实现语句:

<?php

//通过PHP连接MySQL数据库
$connect=mysql_connect("localhost","root","998426");

//选择数据库
mysql_select_db("test");

//设置客户端字符集
mysql_query("set names utf8");

//通过PHP进行select操作
$sql="select * from user";

//执行MySQL语句
$result=mysql_query($sql);

//输出数据
while($row=mysql_fetch_object($result))
{
    echo "<pre>";
    print_r($row->name);
    echo "</pre>";
}

//释放结果集资源并关闭连接
mysql_close($sql);

结果:

user1

wang

user4

user5

MySQL列表化显示:
实现语句:

<?php

header("content-type:text/html;charset=utf-8");

//通过PHP连接MySQL数据库
$connect=mysql_connect("localhost","root","998426");

//选择数据库
mysql_select_db("test");

//设置客户端字符集
mysql_query("set names utf8");

//通过PHP进行select操作
$sql="select * from user";

//执行MySQL语句
$result=mysql_query($sql);

//按表格输出数据
echo "<h1>信息表</h1>";
echo "<table width="700px" border="1px" ";
while($row=mysql_fetch_assoc($result))
{
    echo "<tr>";
    echo "<td>{$row["id"]}</td><td>{$row["name"]}</td>";
    echo "</tr>";
}
echo "</table>";

//释放结果集资源并关闭连接
mysql_close($sql);

结果:
这里写图片描述

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。