
Originally Posted by
ParallelLogic
define('DB_HOST', 'localhost');
works in all cases correct? I don't have to figure out the local address
127.0.0.1 or something do I?
You can use a hostname of "localhost" to connect to MySQL server running on the local computer, yes. Note that "localhost" is not treated exactly the same as "127.0.0.1", though the difference is usually unnoticeable, and beneficial when it is noticeable. When you connect to "localhost", the MySQL driver probably will use UNIX sockets rather than TCP/IP. If you use "127.0.0.1", the driver will use TCP/IP.

Originally Posted by
ParallelLogic
PHP Code:
define('SEARCH', 'bob');
$query = "SELECT "+$SEARCH+" FROM users";
define introduces a constant, not a variable, so you don't reference it with a "$" prefix. Also, the terms after "SELECT" are field names, not values. Also also, variables are interpolated within double quotes, so you don't need to use string concatenation:
PHP Code:
$field="name";
$userName="bob";
$query="SELECT * FROM users WHERE $field='$userName'";
Concatenation is marginally faster than interpolation when used once or twice, but interpolation is more readable and marginally faster when there are multiple values you want to construct the string from. Readability trumps micro-optimization.
In addition to the mysql and mysqli drivers, there's also a MySQL driver for a database abstraction layer called PDO (PHP Data Objects). One nice aspect of PDO is it presents a consistent interface for accessing MySQL, MSSQL, PostgreSQL, SQLite, Oracle and other databases. Not every host's copy of PHP has PDO enabled.
Note that xadrieth's example is intended to illustrate a basic way of connecting to and querying a database. It doesn't perform input validation or sanitization to prevent SQL injection, nor does it handle errors. The approach illustrated by that example is also a little out of date. The more modern approach is to use prepared statements (via mysqli::prepare or PDO::prepare, for example). With prepared statements, you don't need to sanitize data and you can reuse statements.
PHP Code:
function throwOnFalse($result, $stmt) {
if (! $result) {
$err = $stmt->errorInfo();
throw new RuntimeException("$err[2] [$err[0]]", $err[1]);
}
}
try {
$dbConnection = new PDO("mysql:host=localhost;dbname=$dbName", $dbUser, $dbPassword);
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE name=:uname');
throwOnFalse(!$stmt->bindParam('uname', $userName), $stmt);
$userName='bob';
throwOnFalse(!$stmt->execute(), $stmt);
$bob = $stmt->fetch();
$userName='alice';
throwOnFalse(!$stmt->execute(), $stmt);
$alice = $stmt->fetch();
} catch (PDOExeption $exc) {
error_log('PDOException: ' . $exc->getMessage());
} catch (RuntimeException $exc) {
error_log($exc->getMessage());
}
You don't want to have multiple world-readable scripts with your MySQL username and password scattered about. The safest thing to do is define them within a single script with permissions set to mode 0600 and include the script wherever you need a database connection. One really safe implementation is to define a function or object that creates the connection. This way, the username and password are never exposed to any script but the connection script. Here's a sample implementation of this approach:
PHP Code:
function db_connect($driver, $user="default user", $password="dflt p/w", $options=array()) {
$host = isset($options['host']) ? $options['host'] : 'localhost';
switch ($driver) {
case 'mysql':
return mysql_connect($host, $user, $password);
case 'PDO':
return new PDO($options['dsn'], $user, $password, $options);
default:
$dbName = isset($options['db']) ? $options['db'] : '';
return new $driver($host, $user, $password, $dbName);
}
}
Lastly, when you post source code in these forums, enclose it within [code], [php] or [html] tags (whichever is most appropriate) to make it easier to read.