I have a registration script that doesn't work. It used to work but then suddenly it stopped working. I dont know what I've done or what happend. I have tried for like an hour now to find out where the problem is, but I can't seem to find it.
What happens? When I click register I don't get any errors but it doesn't upload to the database:
When I type: $res = mysql_query($query) or die ("ERROR"); it displays ERROR so I think it's related to that code:
//=============Configuring Server and Database=======
$host = 'localhost';
$user = 'root';
$password = '';
//=============Data Base Information=================
$database = 'login';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//=============Starting Registration Script==========
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['pass1']);
$email = mysql_real_escape_string($_POST['email']);
$country = mysql_real_escape_string($_POST['country']);
$rights = '0';
$IP = $_SERVER['REMOTE_ADDR'];
//=============To Encrypt Password===================
//============New Variable of Password is Now with an Encrypted Value========
$query = mysql_query("SELECT username FROM users WHERE username = '".$username."'");
if (mysql_num_rows($query) > 0)
{
echo 'Username or email already in use.';
}
else{
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country',$rights,$IP,NOW())" ;
$res = mysql_query($query);
header("location:load.php");
}
}
I think you are getting the error because you are missing some quotes in your query for two columns wich really looks like not integers
'$email','$country',$rights,$IP,NOW())" //$rights and $ip doesn't have quotes
so your query would look like
"insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country','$rights','$IP',NOW())"
Use mysql_error() in order to see what the error message is. If you haven't changed anything in the script then it's either your database structure has changed or your rights have.
Update:
You don't have quotes around your IP value, which is surprising because you said that query worked until now. Anyway you should also consider saving IPs the RIGHT way. Good luck!
Related
I was working on a register/log in page with a database (first time)
Whenever I register my user, I get the following information in the database:
It is giving me something like a password, but it won't give me my username and email (and i guess password aswell)
Can anyone help me with this?
My php code looks like this:
<?php
session_start();
// connect to database
$db = mysqli_connect('localhost', 'root', '', 'toolsforever');
if (isset($_POST['login_btn'])) {
$username = $db->real_escape_string($username);
$password = $db->real_escape_string($password);
$password = md5($password); // hashed
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 1) {
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header("location: home.php"); //redirect to home page
}else{
$_SESSION['message'] = "Username/password combination incorrect";
}
}
?>
Thanks in advance
PS: Password2 = confirm password for registration password==password2 before they can register.
You are not getting the values from post array so do it like this:
$username = $db->real_escape_string($_POST['username']);
$password = $db->real_escape_string($_POST['password']);
I assume the form fields are names as username and password
It's not just related to retrieval, seems like you need to check the save operation as well. You are storing empty values during registration.
That one worked #danyal Sandeelo. I feel incredible stupid because i've tried an $_POST but i did it like: $username = $_POST['username']; $username = $db->real_escape_string;
I'm currently working on a login system (which works great by using two text fields and the user is then redirected). However, as I am developing a mobile app, it would be much easier to do this in JSON, and I am not entirely sure where to start. What I am basically looking to do is to use a https post request (from my app) so it would request: https://www.example.com/login.php?username=username&password=password
I have created a basic sample, but it's not what I'm looking to do with regards to passing in a parameter via the URL as my code just currently looks for users in the MySQL database and outputs the users in JSON. What I want to be able to do is pass in the username & password parameters, via the URL, and then output a "success" or "error" JSON response if the username/password is in the database or not.
<?php
$host = "localhost";
$username = "root";
$password = "password";
$db_name = "test";
$con = mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$sql = "select * from test_table";
$result = mysql_query($sql);
$json = array();
if (mysql_num_rows($result))
{
while ($row = mysql_fetch_row($result))
{
$json['items'] = $row;
}
}
mysql_close($db_name);
echo json_encode($json, JSON_PRETTY_PRINT);
?>
Edit
I have now started working on another system, which is pretty much what I am looking to do (after I found an example here: http://www.dreamincode.net/forums/topic/235556-how-to-create-a-php-login-with-data-from-mysql-database/) except every time that I request something like https://www.example.com/login.php?username=root&password=password - I get the JSON error 1 code
<?php
$host = "localhost"; // Host name
$db_username = "root"; // Mysql username
$db_password = "password"; // Mysql password
$db_name = "test"; // Database name
$tbl_name = "test_table"; // Table name
// Connect to server
mysql_connect("$host", "$db_username", "$db_password") or die("cannot connect");
// Select the database
mysql_select_db("$db_name") or die("cannot select DB");
// Get the login credentials from user
$username = $_POST['username'];
$userpassword = $_POST['password'];
// Secure the credentials
$username = mysql_real_escape_string($_POST['username']);
$userpassword = mysql_real_escape_string($_POST['password']);
// Check the users input against the DB.
$query = "SELECT * FROM test_table WHERE user = '$username' AND password = '$userpassword'";
$result = mysql_query($query) or die("Unable to verify user because " . mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['total'] == 1) {
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else {
// username and password not found
// failed
$response["failed"] = 1;
// echoing JSON response
echo json_encode($response);
}
?>
Try to change following lines and it should works. I get it to work, as the way you describe it.
1- Here you will get URL parameters and sanitize.
$username = $_GET['username'];
$userpassword = $_GET['password'];
$username = mysql_real_escape_string($username);
$userpassword = mysql_real_escape_string($userpassword);
2- Here you count how many rows you have
Change $row = mysql_fetch_assoc($result);
to $total_rows = mysql_num_rows($result);
3- Here you check if you have at least 1 row.
And change if ($row['total'] == 1) { to if ($total_rows == 1) {
That should give output {"success":1}
Note1: This is to solve your request and question, but does not necessary means the right approach or perfect solution in general.
Note2: I would suggest you think of password hashing, post method in stead of get, use mysqli or PDO in sted of mysql and input sensitization and not use URL to pass username and password. I would suggest you look at this link it describes some of the things I mentioned in my note1.
http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Good day Everyone..
I have an issue that is puzzling me and I can not seem to find a way to solve it. Even the tech support in my hosting service can not solve it.
I have created a small script to do a simple task. I require the employees to log in to perform any said task.
I have tested the application on a development server and the login script works perfectly, but when I place it on the webserver the connection is never established.
I use the same username and passowrd in the dbcon.php file to log in using phpMyAdmin and it works, and I run the queries and they also work.
Here are the files:
1: dbcon.php
<?php
$connect = "mysql:host=localhost;dbname=mdchaara_draiwil_dms;charset=utf8";
$db_user = "dbusername";
$db_pass = "dbpassword";
$db = new PDO($connect,$db_user,$db_pass);
?>
2: login.php:
<?php
session_start();
require "../../_dbcon/_dbcon.php";
//Timezone settings:
$timezone = "Asia/Kuwait";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
// check the username has only alpha numeric characters
if (ctype_alnum($_POST['username']) != true)
{
//if there is no match
$message = "Username must be alpha numeric";
}
//check the password has only alpha numeric characters ***/
if (ctype_alnum($_POST['password']) != true)
{
//if there is no match ***/
$message = "Password must be alpha numeric";
}
else
{
// if we are here the data is valid and we can insert it into database
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
//SQL Injection Precaution:/
$username = stripslashes($username);
$password = stripslashes($password);
try
{
//Select Statement:
$stmt = $db->query("SELECT *
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
$result = $stmt->rowCount();
}
catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
some_logging_function($ex->getMessage());
}
// If result matched $username and $password, there will be one row
if($result==1){
// check if the account is active:
$stmt = $db->query("SELECT id_status
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id_status= $row['id_status'];
}
$stmt = $db->query("SELECT employee_id
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$employee_id= $row['employee_id'];
}
//Check if account is active:
if($id_status == "A"){
// Create Session ID:
$session_id = "";
$_SESSION['sid'] = "";
$session_id = mt_rand(100000, 999999);
$sid_update = $db->query("UPDATE dms_gt_users
SET `session_id`='$session_id'
WHERE username='$username' and password ='$password'");
$_SESSION['sid'] = $session_id;
//Get last login details:
$current_login = date("Y-m-d H:i:s");
$stmt = $db->query('SELECT `last_log_in`
FROM dms_gt_users
WHERE `employee_id` = '.$employee_id);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$last_log_in = $row['last_log_in'];
}
$_SESSION['last_log_in'] = $last_log_in;
//get IP address:
$ip = getenv('REMOTE_ADDR');
//Add login details to Activity Log:
$stmt = $db->query("INSERT INTO dms_activity_log
(`employee_id`, `activity_date_time`, `activity`, `ip_address`)
VALUES ('$employee_id', '$current_login', 'Logged in', '$ip')");
//Add login details to users table:
$stmt = $db->query("UPDATE dms_gt_users
SET `last_log_in`='$current_login'
WHERE username='$username' and password ='$password'");
//update session login
$_SESSION['login']= 1;
//save employee id to session
$_SESSION['employee_id'] = $employee_id;
// redirect to portal home:
header ("Location:../../../home.php");
}
//Account is not Active:
else{
header ("Location:../../../index.php");
}
}
//Username or password are incorrect
else {
header ("Location:../../../index.php");
}
}
?>
What am I doing wrong? and if my code is ok, what should I tell the hosting Tech Support to look for?
Thanks!!
EDIT
#noc2spam: I have updated the connection string as you have advised, I get no errors logged. I var_dump the $db, and I get object(PDO)#1 (0)
It is pretty hard to tell why this is happening without looking into the server itself. I suggest that you enable the Exception mode so that you can see what the problem is. For example:
try {
$connect = "mysql:host=localhost;dbname=mdchaara_draiwil_dms;charset=utf8";
$db_user = "dbusername";
$db_pass = "dbpassword";
$db = new PDO($connect,$db_user,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo 'PDO Exception: '.$e->getMessage();
die();
}
It would be much easier to troubleshoot now. Check if you are getting any error and update the original question with the message if possible. I will edit this answer after that.
IF Roger Ng's answer doesn't solve it, then you may have a firewall blocking your connection. Check your mysql server port... typically 3306.
Check your database's url. Generally, in shared/dedicated hosting environment, DB server and App Server are on different machines. Also, many service providers do not provide mysql cluster services on port 3306. So, please get the correct URL and port of the database from your hosts CPanel or tech support team.
Also, add the App server's IP address to the permitted IP addresses list in Remote MySQL Cpanel interface.
I'm trying to look up user's username using $_GET but not actually seing the result of the query. Here's the code:
<?php
$host = "localhost";
$username = "root";
$password = "toor"; // :)
$database = "db";
$link = mysql_connect($host, $username, $password);
if(!$link){
exit('Could not connect to database: '. mysql_error());
}
$email = mysql_real_escape_string(htmlspecialchars(stripslashes($_GET["e"])));
$query = "SELECT username FROM cc_card WHERE email = '$email'";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$user = mysql_fetch_assoc($result);
echo $user['username'];
} else {
echo "Something's wrong";
}
it's only returnung "Something's wrong". I wanted it to display the username field of the cc_card table where email = email. What am I doing wrong?
If you're getting "Something's wrong" from the posted code it means nowhere in the cc_card table does the email column match the email value you specify in your query.
You need to verify that the contents of your sanitized $email variable do, in fact, exist somewhere in the table. Try:
} else {
echo "Something's wrong";
var_dump($email);
}
To see the contents of the sanitized $email variable and manually query the database from the shell (or phpmyadmin or whatever) to find whether the value you're specifying exists or not. I'm betting it doesn't exist.
You'd better add the error check after the query.
if (!$result) {
die('Error: ' . mysql_error());
}
If no error, then it means there is no matched email in your database.
Using PHP and MySQL to make a login/registration system. Registration is in and I'd say it works alright. However, I'm having some problems with the login page.
No matter what, it just kind of refreshes the page and I'm not sure what's wrong. Here's the loginaccount.php script I have running on the form:
**
EDIT:
**
Thanks for the help so far guys! But I'm still running into a pretty annyoing problem. Now, no matter what, it still doesn't log in, even though now I'm actually getting the error message I set up. Updated code below:
<?php
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
session_start();
$username = $_POST[‘username’];
$password = md5($_POST[‘password’]);
$query = "select * from registerusers where username='$username' and password='$password'";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
$error = "Incorrect login, please try again.";
include "login.php";
echo "<span class=error_message>".$error."</span>";
} else {
$_SESSION['username'] = "$username";
include "login.php";
echo "<span class=success_message>Welcome! You are now logged in.</span>";
}
?>
I can't post comments on questions yet, but I've got a possible reason for your problem.
Since you're only including (and not redirecting) the users to a page, the login page will just stay where it is and just keep including the files - doing the same things over and over. Try header('Location: memberspage.php') instead.