Using MySQL with PHP using mysqli lib

Unix

23 Mar 2015

Using MySQL with PHP using mysqli lib

Preston Garrison 0 Comments

Here is a bunch of simple function that can easily be used to communicate with mysql from php.  These wrap the existing functions to do some typical functions.  One very good thing this allows you to do, is do an update and return the id of the row that was updated.  This is especially useful in order to prevent using locks when selecting a record to update, as well as avoiding race conditions.

 

function ConnectToDatabase() {
     $database_connection = mysqli_connect("server.com", "username", "password", "database"); 
     if (!$database_connection) {
          die('ERROR: Not connected : ' . mysqli_connect_error());
     }


     return($database_connection);

}

function DoSelect($database, $query) {
     return(mysqli_query($database, $query));
}

function DoSelectFields($database, $query) {
     $result =  mysqli_query($database, $query);

     if (!$result) {
          return(false);
     }

     if (mysqli_num_rows($result) == 0) {
         return(false);
     }

     return(mysqli_fetch_assoc($result));

}

function DoUpdate($database, $query) {
     $result = mysqli_query($database, str_replace("SET", "SET id = LAST_INSERT_ID(id),", $query));
     if ($result) {
          return(mysqli_insert_id($database));
     } else {
          return(0);
     }
}



function Escape($instring) {
     return mysql_real_escape_string($instring);
}


function Get($key) {
     if (isset($_REQUEST[$key])) {
          return $_REQUEST[$key];
     } else {
          return("");
     }
}

function Login($database, $login, $password) {
     $sql = "SELECT * FROM users WHERE username='" . Escape($login) . "' AND is_active=1";
     $user = DoSelectFields($database, $sql);

     if (!$user) 
          die("ERROR: login failed user");

     if (sha1( $password . $user['salt']) != $user['password']) {
          die("ERROR: login failed password");
     }

}

 

Preston Garrison