PHP/MySQL form doesn't display output - php

I am new to both PHP and MySQL, however I am currently learning both in order to create a basic website to administrate my RADIUS accounts. (I've switched to using MySQL for user authentication)
I have made a script that inserts user values into the database, however I need to make it so as if a user account already exists, a duplicate can't be created.
I was using a tutorial I found to try and create this, and it does work to an extent. When I add the user when there is no duplicate account, I am returned the message "Successful" however when there is a duplicate user, the page that is returned is blank, and I'm not sure what I'm doing wrong. Its workable, but annoying.
I am also curious if it is possible to create a pool of numbers (These will be IP Address's) and then have it so that when a new user is created, a number from this pool is used, and then removed from that pool. By doing this I hope I could automate assigning IPs to users without having to have someone manually add them every time a new user is created. Currently to achieve a slightly less desirable approach I made another script that displays a list of users IP address's from my table so that one can just add an IP that isn't on this list. Any advise on where I could learn to do this would be greatly appreciated, I don't know where to start.
Below is the php code that I am using, and the html code for the form. Thank you for any help or advise.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_USER','root');
define('DB_PASSWORD','123');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function AuthAccount()
{
$username = $_POST['username'];
$value = $_POST['value'];
$query = "INSERT INTO radcheck(username, attribute, op, value) VALUES ('$username', 'Cleartext-Password', ':=', '$value')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "User added to authentication database";
}
}
function AddAccount()
{
if(!empty($_POST['username']))
{
$query = mysql_query("SELECT * FROM radcheck WHERE username = '$_POST[username]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query) or die(mysql_error()))
{
AuthAccount();
}
else
{
echo "Username already registered";
}
}
}
if(isset($_POST['submit']))
{
AddAccount();
}
?>
Sign-Up Page:
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-Up</title>
</head>
<body id="body-color">
<div id="Sign-Up">
<fieldset style="width:50%"><legend>Registration Form</legend>
<table border="0">
<form method="POST" action="SignUp.php">
<tr>
<td>Username</td><td> <input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td><td> <input type="text" name="value"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</form>
</table>
</fieldset>
</div>
</body>
</html>

Your approach is riddled with problems:
You have introduced a race hazard, whereby two sessions simultaneously attempting to register the same username may both end up passing through the SELECT test before either one has proceeded to INSERT.
If you are using a transactional storage engine (such as Innodb), one can resolve this issue through proper use of transactions and locking reads, but it's far easier simply to impose a uniqueness constraint within the database and leave MySQL to do the rest:
ALTER TABLE radcheck ADD UNIQUE (username)
You can then simply go straight to INSERT and, if the username already exists, an error will be raised that you can handle accordingly.
You are not escaping your string literals when inlining them into your SQL. This is not only a (serious) security vulnerability, but it also introduces a bug whereby your code will break should someone post a username or password that contains a ' character. Passing literal values as parameters to prepared statements avoids these issues.
You are using an ancient PHP extension to access MySQL. It has not been updated since 2006 and its use has been explicitly discouraged in the PHP manual since 2011. As of PHP v5.5, it is deprecated and it will be removed from PHP altogether in a future version. You should switch to either the improved MySQL extension, PHP Data Objects or a third party abstraction layer.
You are storing plaintext passwords in your database. This not only poses a considerable risk to the security of your application in the event that your database is compromised, but it furthermore poses much wider risks to your users (since it is likely that they use the same passwords for other accounts). For their sake, you should always hash every password with salt; you should also be careful to protect their passwords between their browser and your server, e.g. using HTTPS.
As regards the assignment of IP addresses, your question provides no detail on how such addresses are chosen or for what they are used. Usually one leaves such matters to existing services such as DHCP, which only require configuring according to your policy requirements.

i think if(!$row = mysql_fetch_array($query) or die(mysql_error())) is not correct.
I would do it like this:
class db {
public static function dbFactory($host, $dbase, $user, $pass) {
$pdo = new PDO("mysql:host=$host;dbname=$dbase", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
$db = db::dbFactory('localhost','mydbname','myusername','mypassword');
$db->beginTransaction();
try {
$stmt = $db->prepare("SELECT COUNT(*) as cnt FROM radcheck WHERE username = :uname");
$stmt->bindValue(':uname',$_POST[username]);
$stmt->execute();
$res = $stmt->fetch(PDO::FETCH_ASSOC);
if($res['cnt'] == 0) {
// go on ...
}
$db->commit();
} catch (Exception $e) {
$db->rollBack();
}

Related

How to use same query to insert data

I am new at programming.
I am trying to create a simple guestbok.
i have one index page where you can register a firstname, lastname and email.
And if you click on one name you redirect to a new page with id.
How can i now insert text to this ID with the same codeblock using the ID.
My code looks like this.
<?php
require('dbconfig.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=projektone", $username, $password);
//Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Insert to database
$sql = "INSERT INTO user (firstname, lastname, email)
VALUE ('".$_POST["first_name"]."','".$_POST["last_name"]."','".$_POST["email"]."')";
$sql = "INSERT INTO user (guestbok)
VALUE ('".$_POST["guestbok"]."')";
$conn->query($sql);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
header('Location: /');
?>
Thanks in advance
/Daniel
Joining up raw bits of text and passing them on to your database to process is not a good idea. It opens up your system to SQL injection. While it's unlikely that someone could compromise your site when only INSERT statements are exposed in this way, it does mean that:
anyone with an apostrophe in their name will break the logic of the request
you are exposing a method by which someone can carry out a stored XSS attack by submitting javascript to your guestbook
Regarding the SQL Injection problem, there are 2 methods to protect your system - one is to transform the data in which a way that it cannot break the SQL string it is added to (e.g. using mysqli_real_escape_string()) but the recommended approach when using PDO to mediate your code's interaction with the DBMS is to use variable binding. Here you compose your SQL command with placeholders for the data and substitute them at run time.
If your ID is generated from a mysql auto insert id, then you can read the value from $conn->lastinsertid
$stmt=$conn->prepare("INSERT INTO user (firstname, lastname, email)
VALUES (:fnm,:lnm,:eml)");
$stmt->execute(array(
':fnm' => $_POST["first_name"],
':lnm' => $_POST["last_name"],
':eml' => $_POST["email"]));
$id=$conn->lastinsertid();
Your next problem is how to communicate this securely to the page where the user submits their guestbook comment (in your example code you try to do both operations in the same page).
Sending it in a round trip to the browser, as a cookie or as form variable means that it could be tampered with. There are esoteric stateless solutions where you can do this but with the data encrypted or cryptographically signed, however the simplest solution is to use sessions - add session_start() at the top of all your pages and any data you want available across requests can be stored in the $_SESSION superglobal.
(there are security issues relating to sessions as well)
When you receive the POST containing the guestbook data, then you should use an UPDATE user SET guestbook=:gstbk WHERE id=:id_from_session (or you could INSERT it into a seperate table with id as a foreign key)
Lastly, when you output the message the person left in your guestbook, make sure you protect the browser from any nasties in there:
print htmlentities($guestbook);
Ok, probably I managed to get what you need. Put the following two lines in your dbconfig.php:
$conn = new PDO("mysql:host=$servername;dbname=projektone", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
and then require it wherever you need a database connection:
file one:
require('dbconfig.php');
$sql = "sql 1";
$conn->query($sql);
then in another file
require('dbconfig.php');
$sql = "sql 2";
$conn->query($sql);

Security vulnerabilities in code to insert and return last inserted row number

I have the following code which is supposed to insert a row into a DB table "clicks" (consisting 1 Primary AI column "id" and another column "user" which contains the user's sessions id) upon clicking the Like button. For each user assuming they have a session id set from a login I would like to return to them their most recently inserted id from the table. So the first time the button is clicked it will return 1 etc.
I would like this to be accessible to multiple users through a login system. I was wondering if there are any major security vulnerabilities with my code e.g can the results be forged etc?
index.php:
<?php
include 'init.php';
include 'connect.php';
?>
<!doctype html>
<html>
<body>
<?php
$userid = $_SESSION['user_id'];
echo '<a class="like" href="#" onclick="like_add(', $userid,
');">Like</a>';
?>
<script type ="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type ="text/javascript" src="like.js"></script>
</body>
</html>
connect.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "DB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
init.php:
<?php
session_start();
$_SESSION['user_id']='1';
$userid = $_SESSION['user_id'];
include 'connect.php';
include 'like.php';
?>
like.js:
function like_add(userid) {
$.post('like_add.php', {userid:userid}, function(data) {
if (data == 'success'){
add_like($userid);
} else{
alert(data);
}
});
}
like.php:
<?php
function add_like($userid){
include 'connect.php';
$stmt = $conn->prepare("INSERT INTO clicks (user) VALUES (?)");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt = $conn->prepare("SELECT max(id) FROM clicks WHERE user=?");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($click);
$stmt->fetch();
echo $click;
$stmt->close();
}
?>
like_add.php:
<?php
include 'init.php';
if (isset($userid)) {
$userid = $userid;
add_like($userid);
}
?>
Your query might give incorrect results if the same user sends multiple requests almost at the same time, case when your query will not return the currently inserted id. You can use the last_insert_id() mysql function which gives you the last inserted auto-increment value, regardless if meanwhile other requests updated the table.
Also, you don't need to pass the user_id parameter with the ajax request, as you anyway can obtain it from the session. Passing the user_id can be considered a security hole, as anyone can modify the onclick handler and trigger clicks for other users. I'd recommend avoiding as much as possible sending user ids in plain text as response.
To add more security: in your connection script. Change the $servername, $username etc to constants. These don’t need to change, and you don’t want them to be changed.
Do you have any type of checks for your sessions? Sessions are more secure than cookies but they can be hijacked in transit when a user logs in. To add some security to your session, use the session_regenerate_id() function when the user logs in, this will generate a new session id therefore if the users id has been hijacked, it is of no use as it will have changed. There are other checks that can be carried out on sessions to secure them but this is a good quick way of adding an extra level.
#nomistic makes some good suggestions also especially regarding encryption of passwords and other sensitive information. Using the crypt() function or PHP’s password hashing API - http://php.net/manual/en/book.password.php. Is also a good way.
This looks pretty good on the php side. You are using session ids for user verification, and have prepared your SQL inserts. (One question, why are you setting $_SESSION['user_id']='1'? Do you plan on only having one user? That doesn't seem necessary to me)
However, you might want to tighten up your database-side security. It's probably a good idea to set up a different user for public database access, and limit the actions on the database side. For instance, if all they are going to do is select or insert, that user should only have access to do so. I wouldn't use your root account for that. Though it's probably not a huge risk (you are doing pretty well against SQL injection, at least the first two times) just to add another layer is always a good idea.
When dealing with security, it's helpful to think of a "use-case" scenario. What sort of data are you storing? Is it something that somebody really would want? (e.g. is it financial?) It's always a good idea to look at the human element. Would someone want to spend more than a day trying to hack your data (is it worth it for them?).
Also, though it's not evident here, you probably want to make sure you have a good form of encrypting passwords.
Another thought: even if it is minor risk, it's not a bad idea to run daily backups, so you can recover your data in a worst-case scenario.
Edit:
Since it was asked, here's how to setup security at the database side:
First create a new user (following this pattern):
CREATE USER 'newuser'#'localhost' IDENTIFIED BY 'password';
Granting permissions work like this:
GRANT [type of permission] ON [database name].[table name] TO ‘[username]’#'localhost’;
Types of privileges include ALL PRIVILEGES, CREATE,DROP, DELETE, INSERT, SELECT, UPDATE, GRANT OPTION.
If you want to read up on this more, here's the documentation: https://dev.mysql.com/doc/refman/5.1/en/adding-users.html

Mysql Login Form

So I made this basic login form as follows in html.I understand that it is lacking at the moment in security measures, but I just want it to simply be able to login first. Then I will build in the more advanced features.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Jotorres Login Form</title>
</head>
<body>
<form method="post" action="login.php" >
<table border="1" >
<tr>
<td><label for="users_name">Username</label></td>
<td><input type="text"
name="users_name" id="users_name"></td>
</tr>
<tr>
<td><label for="users_pass">Password</label></td>
<td><input name="users_pass"
type="password" id="users_pass"></input></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/>
<td><input type="reset" value="Reset"/>
</tr>
</table>
</form>
</body>
</html>
Then I call login.php. I have a user in the RDS database called "tommytest" with a password of "tommytest" but it isn't working. Keeps saying incorrect username or password. But if I leave the form blank and hit submit it says I am verified.
<?php
// Grab User submitted information
$name = $_POST["users_name"];
$pass = $_POST["users_pass"];
// Connect to the database
$con = mysql_connect("localhost","username","password");
// Make sure we connected succesfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
// Select the database to use
mysql_select_db("ist421test",$con);
$result = mysql_query("SELECT userName AND password FROM users_tbl WHERE userName = '$name'");
$row = mysql_fetch_array($result);
if($row["userName"]==$name && $row["password"]==$pass)
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";
?>
So you have a series of issues here:
You are using mysql_* functions which are deprecated. You should consider using mysqli or PDO.
You are doing absolutely nothing to prevent SQL injection. You should do a quick search on SQL injection here in SO to see how to solve for this.
You are using a plaintext password, when you should be hashing the password. You should look at password_hash() and password_verify() functions in PHP documentation to see how to properly hash your passwords.
You have not enclosed the $name value in single quotes in your SQL. And you are not specifying select fields correctly (like SELECT userName, password ...). Also, you are not handling any errors resulting from your query or you would have seen this. This is actually the root cause for your code not working as expected. You should always check the result of any DB function call to make sure you are getting the expected result before doing any more with it.
You are doing nothing to check that a form value is actually entered. This, along with your bad query result noted above and the fact you are using loose comparisons, give you the validated user text when no values have been input. You really should not even make a query against the database if you have empty POST fields (for either required field).
You also have a cross-site request forgery (CSRF) vulnerability as well. So once you have figured out the basic login functionality, you may want to research on how to use session tokens to mitigate against that risk.
I don't mean to overwhelm you with a bunch of items that are not specific to answering your question. It is clear that you are in the learning mode here, so I just wanted to make sure you had some good guidance on some of the other issues your code currently has beyond the simple SQL syntax issues. Hopefully you can take this information to help you form a better picture of what sort of issues need to be considered when you start working with user logins in a web application.
You are not keeping the password stored safe. Hash+salt needed
Look at your query, you are not checking the combination of username and password, only the username
You should read about SQL Injections
mysql_* is deprecated. Use PDO or mysqli
Now, what might be wrong?
Try printing mysql_error() to debug.
SELECT username,password FROM users_tbl WHERE username='username' AND PASSWORD='password'
Now, if this query results in one row, the combination is correct:
mysql_num_rows() will give you the number of rows.
Again, check out PDO or Mysqli.
Good luck.
Firstly, do consider using a safer password storage method such as crypt(), bcrypt() or PHP's password_hash() function (which has already been addressed).
This line is where the biggest problem is: (using AND instead of a comma for your column names.)
"SELECT userName AND password FROM users_tbl WHERE userName = '$name'"
^^^
Then, you did not quote $name in WHERE userName = $name
Use:
"SELECT username, password FROM users_tbl WHERE username = '$name' AND password='$pass'"
Here is a mysqli_* based version, with the PHP/SQL/HTML form in one file for testing.
(Tested)
<?php
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_NAME', 'xxx');
$mysqli = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("could not connect");
if(isset($_POST['submit'])){
// Grab User submitted information
$name = mysqli_real_escape_string($mysqli,$_POST["users_name"]);
$pass = mysqli_real_escape_string($mysqli,$_POST["users_pass"]);
$result = mysqli_query($mysqli,"SELECT username, password FROM users_tbl WHERE username = '$name' AND password='$pass'");
$row = mysqli_fetch_array($result);
if($row["username"]==$name && $row["password"]==$pass){
echo"You are a validated user.";
}
else{
echo"Sorry, your credentials are not valid, Please try again.";
}
} // if(isset($_POST['submit'])){
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Jotorres Login Form</title>
</head>
<body>
<form method="post" action="" >
<table border="1" >
<tr>
<td><label for="users_name">Username</label></td>
<td><input type="text"
name="users_name" id="users_name"></td>
</tr>
<tr>
<td><label for="users_pass">Password</label></td>
<td><input name="users_pass" type="password" id="users_pass"></input></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit"/>
<td><input type="reset" value="Reset"/>
</tr>
</table>
</form>
</body>
</html>
Footnotes:
Consider using mysqli_* functions with prepared statements or PDO, mysql_* functions are deprecated and will be deleted from future PHP releases.
See also:
crypt(), documentation on bcrypt() on SO, and PHP's password_hash() function.
Instead of the hoops you are jumping, I would do something similar to this, EVEN though this is prone to SQL injection, which I'll talk about afterwards.
SELECT COUNT(*) FROM `users_tbl` WHERE `userName` = '$name' AND `password` = '$pass'
So you would have this
$result = mysql_query("SELECT COUNT(*)
FROM `users_tbl`
WHERE `userName` = '$name' AND `password` = '$pass'");
if (!$result || mysql_num_rows($result) <= 0) {
// NO user found!
} else {
// User found and password matches
}
This is not entirely a safe way of working with SQL - because you are directly injecting the value that a user types in, right to the database query. A hackster could type DROP TABLE users_tbl as his username and potentially empty your database.
On top of that, you are using deprecated mysql_ methods that are being removed completely from PHP - hence the big red box when you look at any online documentation regarding those methods.
http://us2.php.net/manual/en/function.mysql-query.php
I hope this answer helps you understand the query problem, and a little error checking, but before progressing, you should invest some hours into catching up on the modern mysqli and PDO methods.
You're not retrieving "password" correctly on your query, so always is empty $row['password'] and just an empty value will validate.
change your query like
SELECT userName , password FROM users_tbl WHERE userName = '$name'

php username and password validation secure code

I am using WYSIWYG Webbuilder 8 to construct a website. Part of the website will be restricted access to registered users only. To this end I have created a MySQL database. I also have a sign-up form. When a new user wishes to sign-up I would like to have the username automatically checked against the database to make sure it doesn't already exist. I intend doing this using an AJAX function as the WYSIWYG software has this option built in. What I need to build myself and this is where I'm struggling is the validate.php that the AJAX command will go to.
I have something like this at present (please excuse my ignorance!):
<?php
$username = $_POST['data'];
// TODO: lookup username in database...
if ($username == 'user')
{
echo "true";
}
else
{
echo "false";
}
?>
I have no real idea if this is adequate or secure. I have been reading some scary stuff about sql injection and other black arts involving the use of forms and I'd like to avoid pitfalls if possible.
Would some kind soul please have a look at my request and help me out? I'm not a programmer by any stretch of the imagination and I'm way out of my depth here.
Thanks in advance for your help
You want to use something that will handle the chatter between your application and the database for you. One of the best tools available for this today is the PDO library, specifically PDO-MySQL for your usage. It will handle escaping and SQL injection issues for you by using parameterized (prepared) statements
Here's an example of connecting to a database and issuing a query in MySQL
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF-8', 'username', 'password');
$statement = $db->prepare('SELECT user_id FROM users WHERE username = :username LIMIT 1');
$statement->bindValue(':username', $_POST['data']);
$statement->execute();
if (false == $userId = $statement->fetchColumn()) {
// No matching username was found in the database
} else {
// A matching username was found in the database
// $userId contains the matching user ID
}
Knowing how to pass this back to your JS/AJAX integration could be dependent on what framework (if any) you are using and what format you would like that data in

Trying to practice PHP and SQL- I am not sure if I get the logic right

I googled a short tutorial to connect a database and then I wanted to compare the username and password to then can gain access. It is kind of novice coding, but at least I can practice and hopefully pick up programming more.
check.php
<?php
//Need session//
$username = 'root';
$password = 'root';
$host = 'localhost';
$db_name = 'pcart';
$connection = mysql_connect($host, $username, $password) or die('cannot be connected');
mysql_select_db($db_name, $connection) or die ('Could not select database');
$user=$_POST['username'];
$pass=$_POST['password'];
$query = "Select username, password from tbladmins";
$user_result = mysql_query($query);
echo $user_result;
if (mysql_num_rows($user_result)==0)
{
echo "no rows to print";
}
while ($row=mysql_fetch_array($user_result, MYSQL_ASSOC))
{
$checkuser=$row["username"];
$checkpass=$row["password"];
}
mysql_free_result($user_result);
if !($user == $checkuser and $pass == $checkpass)
{
echo'where are you';
$results= mysql_query("Select * from tbladmins;") or die('error connecting to mysql');
if(mysql_num_rows($results)==0)
{
echo "no rows found, nothing to print so i am exiting";
}
print "test successful"
mysql_free_result($results);
}
else
{
echo "Wrong user or password! If you forgot, email Josephine for the username
and password";
}
?>
index.php
<html>
<head>
<title>Partner Portal
</title>
</head>
<body id="partners-page">
<div id="main">
<form method="post" action="Check.php">
<input type="text" name="username" value=""/>
<input type="password" name="password" value=""/>
<input type="submit" name="submit" value="submit">
<input type="reset" name="reset" value="reset">
</form>
forgotten password
</div>
<!--#main-->
</div><!--div partner-page-->
</html>
EDIT
The problem is that it won't show anything when I am testing if username and password match the one in database... So did I overlook anything? Why was the page blank when I tested inputting username and password?
Nice Josephine, that's a great start! Now I know you have heard of the saying, there are a million ways to skin a cat, and this is no exception. There are really a lot of ways to accomplish the above but as of late, this method of doing it have become a bit, how should I say it, un-secure.
Database connection and user management and implementing it all in a secure way is now contained in every PHP framework you can find. This is all done for you so basically what you have to do is fill in the configuration file and you are good to go.
Saying that, it's great to learn how it all ties together and you are on the right track. :D
A framework is there to re-use code that you use in every application, and being a software engineer, we re-use a lot, so you do not want to go and duplicate it all over the place.
Another thing is that the code like this, stays hidden so for instance, I, can't muck it up and I know it's tested properly.
Keep up the good work :D It gets a lot more interesting the deeper you go down the rabbit hole.
Josephine, for the base/groundwork yes. You can always add MD5 / SHA to hash your password for better security.
The only obvious reason I can see that it would fail is the typo here (locah-, instead of localh-):
$locahost = 'localhost';
It's a good start, but it looks like you've still got a long journey ahead of you.
Some of the obvious things are:
1) Why name a variable containing 'localhost' as $localhost? It would make more sense to have called this $host
2) indeed, the variables passed to mysql_connect are only ever used for mysql_connect - why did you not use literals? Why are the variable declarations and function invocation split across two separate include files?
3) Why have you not provided a specific error message? One was probably generated at some point during the execution - if you saw it then you should have provided it in your post. If you didn't see it, then spend some time thinking about why (and make sure you will see it next time).
4) Once you've got it working on your test rig, how do you think the script is going to perform when you've got a few thousand rows in tbladmin? While performing complex tasks using non-procedural code can result in code that is difficult to debug, pushing more logic down the tier almost always improves performance. Consider:
$qry = "SELECT * from tbladmins WHERE username='"
. mysql_real_escape_string($_REQUEST['username'], $connection)
. "' AND password = '"
. mysql_real_escape_string($_REQUEST['password'], $connection)
. "'";
5) using inline code within include files is a messy practice - if you restrict include files to only declaring functions, classes and constants then explicitly invoke them at the right time, then you'll save yourself a lot grief as your programs become more complex.
6) include files are not a substitute for modular programming - see also (5) above.
Good luck.

Categories