Copyright © 2010 Olebox – Shaun Oleson. All Rights Reserved. Snowblind by Themes by bavotasan.com. Powered by WordPress.
I have written a function to make it easier to execute queries against a MySQL server. I’m posting it here with the hope that it may help other developers that are either learning or looking for a more efficient way to execute SQL statements. I may convert this to a class in the near future, although there isn’t much of an advantage to this from what I’ve seen.
<?php
//if accessing the file directly, stop execution, this file must be included.
if (!defined(‘IN_SITE’)) { exit; }function getmysql($sql_str) {
$mysql_username = “database_username”;
$mysql_password = “database_password”;
$mysql_database = “database_name”;
$mysql_host = “localhost”;$conn = mysql_connect($mysql_host, $mysql_username, $mysql_password) or die(‘error connecting’);
$db = mysql_select_db($mysql_database) or die(‘error with db’);
$sql = $sql_str;
$result = mysql_query($sql) or die(mysql_error());return $result;
}
?>
If you add the previous code to a PHP include, you will be able to execute SQL statements using the following syntax. This will allow you to specify the database information in one place.
<?php
$result = getmysql(“SELECT username, password FROM USERS;”);while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$username = $row['username'];
$password = $row['password'];
// add actions to take during mysql recordset result
}
?>
Hopefully, you will find this useful. If you have any feedback or questions, feel free to leave a comment.
