The script was my attempt to write what a minimum a PHP database script ought to look like. Some goals were: no die(), clear logic, thorough error checking, separation of connection and response (reporting an error is also a response), and basic security. I should also show good programming habits and practices.
I have some questions:
- should it be in three parts: connection, query/fetch, and display data? (so we could show fetching one or may rows for example)
- should it be database independent in some way or does that complicate it too much?
- should things be put in functions so they are more reusable (e.g. connect() and query(), fetch())
Code: Select all
<?php
// initialize variables
$errmsg = '';
$row = array();
// Connect to server
$con = mysql_connect("localhost","don't_post_usernames","don't_post_passwords");
if (mysql_errno()) {
$errmsg = 'Could not connect:' . mysql_error();
} else {
// Select database.
mysql_select_db("database_name");
if (mysql_errno()) {
$errmsg = 'Could not select:' . mysql_error();
} else {
// Setup and do query
// filter untrusted post variable
$username = preg_replace('/[^a-zA-Z0-9]/', '', $_POST['username']);
// escape untrusted post variable
$username = mysql_real_escape_string($username); // changed - thanks Mordred
$sql1 = "SELECT * FROM user WHERE username='$username'";
$result1 = mysql_query($sql1);
if (mysql_errno()) {
$errmsg = 'Query failed:' . mysql_error();
} else {
$row = mysql_fetch_assoc($result);
}
}
}
// now the response
if ($errmsg) {
// error goes here
echo "Error: $errmsg<br/>";
} else {
// success goes here
dump($row);
}
// handy for debugging
function dump($value) {
echo '<pre>' . print_r($value, 1) . '</pre>';
}