网络编程
位置:首页>> 网络编程>> 数据库>> 玩转MySQL中的外键约束之PHP篇(3)

玩转MySQL中的外键约束之PHP篇(3)

 来源:asp之家 发布时间:2010-03-18 10:20:00 

标签:MySQL外键约束,MySQL约束,外键


三、利用PHP 5以级联方式更新数据库

好了,现在开始详细介绍如何使用流行的服务器端脚本语言PHP 5来以级联方式更新我们的示例表。为此,我们需要编写允许我们访问上面定义的InnoDB表的代码,就本例而言,我们使用PHP 5的MySQL抽象类来达此目的。下面给出具体的代码:


class MySQL
{
private $result = NULL;
private $link = NULL;

//连接到MySQL

public function __construct($host, $user, $password, $database)
{
if (FALSE === ($this->link = mysqli_connect($host, $user, $password, $database)))
{
throw new Exception('Error : ' . mysqli_connect_error());
}
}

//执行查询

public function query($query)
{
if (is_string($query) AND empty($query) === FALSE)
{
if (FALSE === ($this->result = mysqli_query($this->link, $query)))
{
throw new Exception('Error performing query ' . $query . ' Error message :' .mysqli_error($this->link));
}
}
}

//从结果集返回数据

public function fetch()
{
if (FALSE === ($row = mysqli_fetch_object($this->result)))
{
mysqli_free_result($this->result);
return FALSE;
}
return $row;
}

//获取插入ID

public function getInsertID()
{
return mysqli_insert_id($this->link);
}

//结果集中的行数

public function countRows()
{
if ($this->result !== NULL)
{
return mysqli_num_rows($this->result);
}
}

//关闭数据库连接

function __destruct()
{
mysqli_close($this->link);
}
}

如上所示,上面定义的MySQL抽象类十分简单,它提供了许多常用的方法,用于执行查询、统计结果集行数以及获取插入ID。需要格外注意的是,这个类内部使用了PHP扩展mysqli来跟MySQL打交道,所以整体看来是很容易理解的。

好了,我们已经定义了一个可以用于跟MySQL数据库相交互的PHP 5类,现在我们要做的就是利用它的API对前面定义的InnoDB表执行级联更新。



0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com