i am new in terms of php. i am now creating a simple program which is similar as a login page. may you please help me to do my coding, i have mysql table named user which has 3 column userid, email and password. my primary is userid and it is an auto increment. how can i have code which is, the column email should no duplication or no same email. i have already code for avoiding empty fields i don't know now how to do about the duplication..
here is my sample code:
<?php
if(isset($_POST['submit'])){
$dbhost = 'localhost';
$dbuser = 'root';
$conn = mysql_connect($dbhost, $dbuser);
mysql_select_db('dtr');
if(! $conn ){
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ){
$email = addslashes ($_POST['email']);
$password = addslashes ($_POST['password']);
}
else{
$email = $_POST['email'];
$password = $_POST['password'];
}
//validation
if($email == ''){
echo "empty ang email" ?></br><?php ;
return false;
}
if($password == ''){
echo "kailangan may password ka\n" ?></br><?php ;
return false;
}
---------------------->//select * table where username=user
{
$sql = "INSERT INTO user "."(email, password) "."VALUES('$email','$password')";
$retval = mysql_query( $sql, $conn );
}
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
}
?>
help me plz..
you can try:
$sql = "SELECT userid from users WHERE email = ". $_POST["email"];
if (mysql_num_rows(mysql_query($sql, $con)) >= 1)
{
echo "That email you provided seems to be already used";
return;
}
And please thing about using a different db extension since mysql is deprecated as of PHP V. 5.5. It will give you better security features with binding and prepared statements.
Simply use this, I think it should give u help:
$name = $_POST[name];
$pass = $_POST[pass];
$user = "SELECT * from users WHERE email = '".$email."'";
$result = mysql_query($user);
if(mysql_num_rows($result)>0){
return "$result";
}
else{
mysql_query("INSERT INTO users(email, pass) VALUES ('$email', '$pass')");
}
Related
This script should get some Variables of a submit form. Then it should check them from the DB and see if password and username match, if not it should send them back to the login page.
I already tried letting it check if the username exist via:
$this = "Select name from user where name = '".$_POST['name']"'";
$query = mysqli_query($conn,$this);
while( $row = mysqli_fetch_assoc($query)){
if (empty($row['name']){
do this;
}
}
But still got a blank page.
<?php
include "private/dbconnection.inc.php";
$conn = mysqli_connect($servername, $username, $password, $db);
if(!$conn){
die ("Verbindung fehlgeschlagen: ". mysqli_connect_error());
}
$selectpw = "SELECT * from user where name = '".$_POST['name']." ' ";
$pwcheck = mysqli_query($conn,$selectpw);
$selectname = "SELECT name from user where name = '".$_POST['name']."'";
$namecheck = mysqli_query($conn,$selectname);
while ( $row = mysqli_fetch_assoc($pwcheck)){
if ( $_POST['password'] === $row['password'] && $_POST['name'] === $row['name'] ){
header("Location:https://myhost.de/xxx/this/user.php");
}
else{
header("Location:https://myhost.de/xxxx/prototyp1/");
}
}
mysqli_close($conn);
?>
The script should check if the user is valid for login if hes not he should be send back to login. If hes valid he gets to another page.
But it only works with usernames the mysql knows with other usernames im stuck on the php page and it just shows a blank screen.
As Obsidian said, your code is potentially vulnerable to SQL injection, therefore it would be more suitable to use PDO. This can be achieve like so in the basic code example below.
<?php
include "private/dbconnection.inc.php";
try {
$db = new PDO('host=' . $server_name . ';dbname=' . $database . 'charset=utf-8;', $username, $password);
}
catch(PDOException $e)
{
throw $e; // Throw the PDOException if something failed
}
if(isset($_POST['username']) && isset($_POST['password']))
{
if(!empty($_POST['username'] && !empty($_POST['username'])
{
$query = $db->prepare('SELECT password FROM users WHERE username = ?');
$query->bindParam(1, trim($_POST['username']));
if($query->execute())
{
$password = $query->fetchColumn();
if($_POST['password'] == $password)
{
header('Location: https://myhost.de/xxx/this/user.php');
} else {
header('Location: https://myhost.de/xxxx/prototyp1/');
}
}
}
}
?>
<?php
$server_host = "host";
$server_username = "username";
$server_password = "password";
$server_dbName = "data base name";
$player_username = $_POST ["usernamePost"];
$player_password = $_POST ["passwordPost"];
$player_displayName = $_POST ["displayNamePost"];
$conn = new mysqli ($server_host, $server_username, $server_password, $server_dbName);
if (!$conn) {
echo "Error connecting to the server.";
}
$query_code = "SELECT Username FROM users WHERE Username = '{$_POST[usernamePost]}'";
$result_login = mysqli_query ($conn,$query_code);
$anything_found = mysqli_num_rows ($result_login);
if ($anything_found > 0) {
echo "An account with this username or display name already exsists, please choose another.";
}
if ($anything_found <= 0) {
$sql = "INSERT INTO users (Username, Password, Display_Name)
VALUES ('".$player_username."','".$player_password."','".$player_displayName."')";
$result = mysqli_query ($conn,$sql);
if ($result) {
echo "You may now login.";
}
if (!$result) {
echo "Error.";
}
}
?>
I'm using the Unity Engine to display the echoed result, does this script seem that it will echo "An account with this username or display name already exsists, please choose another." if there is already a username with the username entered? Also, would it echo "You may now login." if the account was created?
I made this script myself, I'm new to this PHP stuff. I'd appreciate it if someone looked this code over and explained to me why this isn't working.
The logic is wrong. Conditional statements are hanging dangerously :-)
Use this
<?php
$server_host = "host";
$server_username = "username";
$server_password = "password";
$server_dbName = "data base name";
$player_username = $_POST ["usernamePost"];
$player_password = $_POST ["passwordPost"];
$player_displayName = $_POST ["displayNamePost"];
$conn = new mysqli ($server_host, $server_username, $server_password, $server_dbName);
if (!$conn) {
echo "Error connecting to the server.";
}
else{
$query_code = "SELECT Username FROM users WHERE Username = '{$_POST[usernamePost]}'";
$result_login = mysqli_query ($conn,$query_code);
$anything_found = mysqli_num_rows ($result_login);
if ($anything_found > 0) {
echo "An account with this username or display name already exsists, please choose another.";
}
elseif ($anything_found <= 0) {
$sql = "INSERT INTO users (Username, Password, Display_Name)
VALUES ('".$player_username."','".$player_password."','".$player_displayName."')";
$result = mysqli_query ($conn,$sql);
if ($result) {
echo "You may now login.";
}
else{
echo "Error.";
}
}
}
?>
<?php
if(isset($_POST['btn-signup'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error)
{
die("Connection failed :" . $conn->connect_error);
}
$uname = trim($_POST['uname']);
$email = trim($_POST['email']);
$upass = trim($_POST['pass']);
$mobile = trim($_POST['mobile']);
$fee = trim($_POST['fee']);
$uname = strip_tags($uname);
$email = strip_tags($email);
$upass = strip_tags($upass);
$mobile = strip_tags($mobile);
$fee = strip_tags($fee);
$role = "user";
// check email exist or not
$query = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($query);
$count = mysqli_num_rows($result); // if email not found then proceed
if ($count==0) {
$query = "INSERT INTO users(username,email,password,mobile,fee,role) VALUES('$uname','$email','$upass','$mobile','$fee','$role')";
$res = mysqli_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "successfully registered, you may login now";
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later..." .mysql_error();
}
} else {
$errTyp = "warning";
$errMSG = "Sorry Email already in use ...";
}
mysqli_close($conn);
}
?>
whenever i click on submit button it always give me "something went wrong error" even i check for the error that has to be "sorry email already in use" but it always showing "something went wrong".
i use session also. i am newbie in php and creating a session based login system for different role such as admin and student.
please give me solution as soon as possible thank you :)
Use only "mysqli_" or "mysql_", recommended is "mysqli_"
You are connecting database with "mysqli_" and fetching the result set using "mysql_"
Learn the Difference MYSQL vs MYSQLi vs PDO
I have seen your code.
Please check the syntax of Insert query once , print the query and run in mysql db and see if it run fine or not.
I think this will resolve your issue.
I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user
I've been following a login system tutorial. You can find it here. There are 2 parts of coding C# and PHP. The C# part is working fine but my PHP part returning error. Here is my PHP code:
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
It seems the error comes from $result_id but I'm not sure?
You are true, the error is from $result_id, because your SQL statement has problem and there are extra stuff to fix.
You have put users table in two single quotes, it is wrong.
Your code is:
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
It should be with out quotes:
$SQL = "SELECT * FROM users WHERE Email = '" . $Email ."'";
You have wrote:
if ($Total){
It should check how many users record found, typically it should find only 1 record and return 1, therefore change it to:
if ($Total == 1){
Note1:
But when this is said, it does not mean the code is perfect, you should further develop your code to fulfill nowadays requirement. I would suggest you think of password hashing, use mysqli or PDO in sted of mysql and input sensitization. I would suggest you look at this link it describes some of the things I mentioned.
Note2:
I was able to write you a total solution with mysqli/PDO etc, but I wanted only to point the errors I have catch so far in your code so you can learn from your mistakes and develop your self.
And in general read about security principles, check this page.
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
This is another simple way where you can create user log in, it is
more secure than the one you have at the moment. And you should
protect your code from sql injections.
<?php
if (isset($_POST['email'], $_POST['password']) === true )
{
require 'connection.php';
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$sql = "SELECT * FROM users WHERE email= '$email'";
$result = mysqli_query($connection,$sql);
if (mysqli_num_rows($result))
{
if( $email == $row['email'] && $password == $row['password'])
{ //use session to check if user is logged in
if (!isset($_SESSION['loggedin']))
{
//you can set session of user's log in details
//you can redirect to user profile
}
else
//already log in, redirect to user profile
}
else
echo "Incorrect Email or Password.";
}
else
echo "Incorrect Username or Password.";
mysqli_close($connection);
}
else
{
echo "Oops, something went wrong!";
?>