Here is a simple mysqli solution for you:
$db = new mysqli('localhost','user','password','database'); $resource = $db->query('SELECT field FROM table WHERE 1'); $row = $resource->fetch_assoc(); echo "{$row['field']}"; $resource->free(); $db->close();
If you grab a few lines, I do it like this:
$db = new mysqli('localhost','user','password','database'); $resource = $db->query('SELECT field FROM table WHERE 1'); while ( $row = $resource->fetch_assoc() ) { echo "{$row['field']}"; } $resource->free(); $db->close();
With error handling: If there is a fatal error, the script exits with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user. if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error); $db = new mysqli('localhost','user','password','database'); $resource = $db->query('SELECT field FROM table WHERE 1'); if ( !$resource ) die('Database Error: '.$db->error); while ( $row = $resource->fetch_assoc() ) { echo "{$row['field']}"; } $resource->free(); $db->close();
With exception handling try / catch:. This allows you to handle any errors in one place and possibly continue execution if something fails, if necessary.
try { if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error); $db = new mysqli('localhost','user','password','database'); $resource = $db->query('SELECT field FROM table WHERE 1'); if ( !$resource ) throw new Exception($db->error); while ( $row = $resource->fetch_assoc() ) { echo "{$row['field']}"; } $resource->free(); $db->close(); } catch (Exception $e) { echo "DB Exception: ",$e->getMessage(),"\n"; }
source share