<?php function get_user_id( $name ) { $db = mysql_connect( 'localhost', 'root', 'password' ); mysql_select_db( 'users' ); $res = mysql_query( select id from users where login='.$name.' ); while( $row = mysql_fetch_array( $res ) ) { $id = $row[0]; } return $id; } var_dump( get_user_id( 'jack' ) ); ?>
注意使用了 mysql_connect 函数来实现php直接使用mysql。还要注意查询,其中使用字符串连接来向查询添加 $name 参数。
该技术有两个很好的替代方案:pear db 模块和 php data objects (pdo) 类。两者都从特定数据库选择提供抽象。因此,您的代码无需太多调整就可以在 ibm? db2?、mysql、postgresql 或者您想要连接到的任何其他数据库上运行。
使用 pear db 模块和 pdo 抽象层的另一个价值在于您可以在 sql 语句中使用 ? 操作符。这样做可使 sql 更加易于维护,且可使您的应用程序免受 sql 注入攻击。
使用 pear db 的替代代码如下所示。
清单 2. access/get_good.php
<?php require_once(db.php); function get_user_id( $name ) { $dsn = 'mysql://root:password@localhost/users'; $db =& db::connect( $dsn, array() ); if (pear::iserror($db)) { die($db->getmessage()); } $res = $db->query( 'select id from users where login=?',array( $name ) ); $id = null; while( $res->fetchinto( $row ) ) { $id = $row[0]; } return $id; } var_dump( get_user_id( 'jack' ) ); ?>
注意,所有php直接使用mysql的地方都消除了,只有 $dsn 中的数据库连接字符串除外。此外,我们通过 ? 操作符在 sql 中使用 $name 变量。然后,查询的数据通过 query() 方法末尾的 array 被发送进来。
http://www.bkjia.com/phpjc/446326.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/446326.htmltecharticle我们在进行 清单 1. access/get.php <?php functionget_user_id($name) { $ db = mysql_connect ('localhost','root','password'); mysql_select_db('users'); $ res = mysql_query (...
