0

Hello pls I want migrate the following code to mysqli. Pls help out, it's login functions. The first function gets the user_id from the database while the second function check if the username and password match for that user from the user_id.

function user_id_from_usernam­e($username){
   $username = sanitize($username);
   return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id');
}

function login($username, $password){
  $user_id = user_id_from_username($username);
  $username = sanitize($username);
  $password = md5($password);
  $query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
  return  ( mysql_result($query­, 0) == 1)? $user_id : false;
}
t.niese
  • 39,256
  • 9
  • 74
  • 101
techtech
  • 11
  • 1
  • 3
  • please avoid mysql_* function as these are now deprecated in php 7 – lazyCoder Apr 20 '17 at 06:02
  • php version pls sepcify ? – Ria Sen Apr 20 '17 at 06:02
  • 1
    format it properly please –  Apr 20 '17 at 06:03
  • And while you're at it, use `mysqli::prepare()` instead of `query()`. And use proper password hashing algorithms, `md5()` isn't safe anymore. And **formatting your code** makes it all the much easier to read and troubleshoot! – Qirel Apr 20 '17 at 06:05
  • 1
    @Learner php 5+ – techtech Apr 20 '17 at 06:05
  • You just wanna change the query from mysql to mysqli? – Brijesh_yadav Apr 20 '17 at 06:08
  • When ever you ask a question, you should at least post some readable code and not such a mess. Why should someone take the time to give you an answer if you don't take the time to format your code. – t.niese Apr 20 '17 at 06:12
  • **WARNING**: Writing your own access control layer is not easy and there are many opportunities to get it severely wrong. Please, do not write your own authentication system when any modern [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with a robust [authentication system](https://laravel.com/docs/5.4/authentication) built-in. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and **never store passwords with a uselessly weak hash like MD5**. – tadman Apr 20 '17 at 06:22

1 Answers1

0

The correct query form for the mysqli_query is :

mysqli_query($connection_variable,"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'");