login help php mysqli

For security, I use a login.html form, a login.php page and a validate. If this is not the best way in mysqli, feel free to tell me a better way. Rewriting a mysql site in mysqli and want to use best methods. Thanks.

This won’t work. Any idea why?

login html form

[php]


Web Site Administration

Please log in below

User Name:


Password:


[/php]

here is the actual login connector

[php]<?php

function login();

// server info
$server = ‘localhost’;
$username = ‘foode_name’;
$pass = ‘whatever’;
$db = ‘foode_table’;

// connect to the database
$mysqli = new mysqli($server, $username, $password, $db);

//show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);

?>[/php]

and here is the validate. I’m trying to set the session as the userid or username, but need to use this connector/validate to get to the admin table to verify, right? Or not?

[php]<?php
session_start();
include (“login.php”);
login();

if(isset($_POST[‘submit’]))
{
$username = trim($_POST[‘username’]);
$password = trim($_POST[‘password’]);
$query = “SELECT username, password FROM admins WHERE username=’$username’ AND password=’$password’”;
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 )
{
$_SESSION[‘userid’]=$row[‘userid’];
header(“Location: admin.php”);
echo ‘hi there’;
exit;
}
else
{
echo ‘oops can not do it’;
}
}
?>[/php]

What doesn’t work? Do you get any error messages?

For security you should also use parameterized queries, your current code is vulnerable to sql injection meaning anyone and everyone can read/dump your database.

Thanks. Spent hours rewriting and researching it yesterday. Any examples online you can direct me to? Not trying to get someone to write it for me but don’t know which tutorial is best…

Modified several times so I don’t remember error.

Sponsor our Newsletter | Privacy Policy | Terms of Service