I have been working with MYSQL in the past and am no expert but have managed to produce a simple MySQL login script. However I am aware that my script is basic and outdated, and that I should be using MYSQLI,
However MYSQLI doesn't really make any sense to me as I have tried the following code in MySQL but I can't seem to get it to work and I get undefined index errors.
<?php
session_start();
include("config.php");
if (mysqli_connect_errno())
{
echo 'MySQLi Connection was not established:';
}
// checking the user
$myusername = mysqli_real_escape_string($conn,$_POST[‘myusername’]);
$pass = mysqli_real_escape_string($conn,$_POST[‘mypassword’]);
$sel_user = 'select * from supplier_users where username=’$myusername’ AND password=’$pass';
$run_user = mysqli_query($conn, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0){
$_SESSION[‘user’]=$myusername;
echo “success”;
}
else {
echo “fail”;
}
?>
here is my MySQL login script which works fine:
<?php
session_start();
include("config.php");
$tbl_name="internal_users";
$tbl_name2="supplier_users";
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql = "select * from $tbl_name where username = '$myusername' and password = '$mypassword'
union
select * from $tbl_name2 where username = '$myusername' and password = '$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if($count==1){
session_start();
include("variables.php");
if($result){
$sql2 = "UPDATE $tbl_name2 SET online = 'online' WHERE online = 'offline' AND username = '$myusername'";
$result2=mysql_query($sql2);
$sql21 = "UPDATE $tbl_name SET online = 'online' WHERE online = 'offline' AND username = '$myusername'";
$result21=mysql_query($sql21); }
else
$_SESSION['val']=1;
header("location:../dashboard.php");
}
else {
$_SESSION['message2'] = '<div id="message_box2"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">✖</div><h23>Oooops!</h23><p>The Username and Password Combination do not match. Please try again.</p> </div>';
header("location:../index.php");
}
ob_end_flush();
?>
my config.php file looks like this:
<?php
$host="localhost";
$username="mark";
$password="password";
$db_name="hewden1";
$conn = mysql_connect($host, $username, $password) or die("Could Not Connect to Server");
$db = mysql_select_db($db_name)or die("Cannot Connect the Database");
?>
my question is, could someone please show me how I can convert my simple login script from MYSQL to MYSQLI and make it more secure in the way that I am trying to do above? I really would appreciate anyone's help with this as I am really struggling to understand.
Thanks