当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP 数据库 常见问题小结第1/3页

PHP 数据库 常见问题小结第1/3页

2019年05月04日  | 移动技术网IT编程  | 我要评论

现在我不是获得最大的 id 值,而是直接使用 insert 语句来插入数据,然后使用 select 语句来检索最后插入的记录的 id。该代码比最初的版本及其相关模式要简单得多,且效率更高。

问题 3:使用多个数据库

偶尔,我们会看到一个应用程序中,每个表都在一个单独的数据库中。在非常大的数据库中这样做是合理的,但是对于一般的应用程序,则不需要这种级别的分割。此外,不能跨数据库执行关系查询,这会影响使用关系数据库的整体思想,更不用说跨多个数据库管理表会更困难了。

那么,多个数据库应该是什么样的呢?首先,您需要一些数据。清单 7 展示了分成 4 个文件的这样的数据。


files.sql:
复制代码 代码如下:

create table files (
id mediumint,
user_id mediumint,
name text,
path text
);

load_files.sql:
复制代码 代码如下:

insert into files values ( 1, 1, 'test1.jpg', 'files/test1.jpg' );
insert into files values ( 2, 1, 'test2.jpg', 'files/test2.jpg' );

users.sql:
复制代码 代码如下:

drop table if exists users;
create table users (
id mediumint,
login text,
password text
);

load_users.sql:
复制代码 代码如下:

insert into users values ( 1, 'jack', 'pass' );
insert into users values ( 2, 'jon', 'pass' );


清单 7. 数据库文件
在这些文件的多数据库版本中,您应该将 sql 语句加载到一个数据库中,然后将 users sql 语句加载到另一个数据库中。用于在数据库中查询与某个特定用户相关联的文件的 php 代码如下所示。


复制代码 代码如下:

<?php
require_once("db.php");

function get_user( $name )
{
$dsn = 'mysql://root:password@localhost/bad_multi1';
$db =& db::connect( $dsn, array() );
if (pear::iserror($db)) { die($db->getmessage()); }

$res = $db->query( "select id from users where login=?",
array( $name ) );
$uid = null;
while( $res->fetchinto( $row ) ) { $uid = $row[0]; }

return $uid;
}

function get_files( $name )
{
$uid = get_user( $name );

$rows = array();

$dsn = 'mysql://root:password@localhost/bad_multi2';
$db =& db::connect( $dsn, array() );
if (pear::iserror($db)) { die($db->getmessage()); }

$res = $db->query( "select * from files where user_id=?",
array( $uid ) );
while( $res->fetchinto( $row ) ) { $rows[] = $row; }

return $rows;
}

$files = get_files( 'jack' );

var_dump( $files );
?>


清单 8. getfiles.php
get_user 函数连接到包含用户表的数据库并检索给定用户的 id。get_files 函数连接到文件表并检索与给定用户相关联的文件行。

做所有这些事情的一个更好办法是将数据加载到一个数据库中,然后执行查询,比如下面的查询。


复制代码 代码如下:

<?php
require_once("db.php");

function get_files( $name )
{
$rows = array();

$dsn = 'mysql://root:password@localhost/good_multi';
$db =& db::connect( $dsn, array() );
if (pear::iserror($db)) { die($db->getmessage()); }

$res = $db->query(
"select files.* from users, files where
users.login=? and users.id=files.user_id",
array( $name ) );
while( $res->fetchinto( $row ) ) { $rows[] = $row; }

return $rows;
}

$files = get_files( 'jack' );

var_dump( $files );
?>


清单 9. getfiles_good.php
2

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网