We are runningListing 1. Access/get. php
- <?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' ) );
- ?>
Note that the mysql_connect function is used for PHP to directly use MySQL. Pay attention to the query. Use string connection to add the $ name parameter to the query.
This technology has two good alternatives: the pear db module and the PHP Data Objects (PDO) class. Both provide abstraction from the choice of a specific database. Therefore, your code can be stored in IBM without too many adjustments? DB2? , MySQL, PostgreSQL, or any other database you want to connect.
Another value of using the pear db module and the PDO abstraction layer is that you can use it in SQL statements? Operator. This makes SQL easier to maintain and protects your applications from SQL injection attacks.
The alternative code for using pear db is as follows.
Listing 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' ) );
- ?>
Note that all PHP uses MySQL directly, except for the database connection strings in $ dsn. In addition, we pass? The operator uses the $ name variable in SQL. Then, the queried data is sent in through the array at the end of the query () method.