PHP Form Validator/MySQL Insert - php

I have written a small PHP file that gets the information that was posted to it, then checks to make sure it is no empty. If it isn't empty, it checks to make sure the username doesn't already exist. If it does, it redirects. If not, it adds the information to the MySQL database. I don't know what the problem is, but when attempting to navigate to it after pressing the submit button on the form, the browser displays an error saying that the page cannot be displayed. Here is the code.
<?php
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$username = $_POST['user'];
$password = $_POST['pass'];
$con = mysql_connect("localhost","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("zach_blogin", $con);
$query="SELECT username FROM members WHERE username=$username";
if (mysql_num_rows($username) > 0 ) {
header("Location: register.php?invalid");
} else {
$sql=("INSERT INTO members (username, password, FirstName, LastName, Email)
VALUES ($username, $password, $firstname, $lastname, $email)");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else {
header("Location: register.php?required");
}
?>

You are not executing the query:
$query="SELECT username FROM members WHERE username=$username";
//You need to execute the query here before you get num of rows.
if (mysql_num_rows($username) > 0 ) // also mysql_num_query takes an object.
Something like:
$query="SELECT username FROM members WHERE username=$username";
if(($result = mysql_query($query)) !== false) {
if (mysql_num_rows($result) > 0 ) {
.....
}
}

Change this
if (mysql_num_rows($username) > 0 ) {
to
if (mysql_num_rows(mysql_query($query)) > 0 ) {

Related

PHP Login script only works with usernames known to mysql

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/');
}
}
}
}
?>

Two queries using Mysqli

Problem:
Trying to run two MySQLi queries against the database but results always into a failure message.
Code (PHP):
// Checks whether submit button has been pressed
if (isset($_POST['submit']))
{
// Gets values from form fields
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
// Selects e-mail in database
$query = "SELECT * FROM userlogin WHERE email = '{$email}'";
$result = mysqli_query($link, $query) or die('Error [' . mysqli_error($link) . ']');
// Checks whether e-mail exist
if (mysqli_num_rows($result) != 0)
{
// Register new user
$query = "INSERT INTO
userlogin
(username, password, email, regdate)
VALUES
('James','{$password}', '{$email}', NOW())
";
// Submit query to database
$result = mysqli_query($link, $query) or die('Error [' . mysqli_error($link) . ']');
// Return success message
header('Location: index.php?notification=success');
}
else
{
// Return failure message
header('Location: index.php?notification=fail');
}
}
What am I missing? Any advice is appreciated.
Shouldn't this
mysqli_num_rows($result) != 0
be
mysqli_num_rows($result) == 0
One issue is
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
and should be
$email = mysqli_real_escape_string($link,stripslashes($_POST['email']));
$password = mysqli_real_escape_string($link,stripslashes($_POST['password']));

how to avoid duplicating in php

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')");
}

PHP Only Selecting First Row?

I have a quick login form that i made for school the only problem is that when i try and login everything worked perfectly when i want to log into the first user (Username: hbutler Password: password) However when i try to login to my other accounts i get the page refresh which i have set it do if it is incorrect here is my code :
<?PHP
//Create the connection…
//("where the database is", 'Database login' , 'database password' , "Database name")
$con=mysqli_connect("", 'root', 'root', "Social");
//Check our connection…
if (mysqli_connect_errno($con))
{
echo " Sorry Mate";
}
$username = $_POST['username'];
$password = $_POST['pawd'];
$result = mysqli_query($con, "SELECT * FROM User_info");
$row = mysqli_fetch_array($result);
$value = $row['username'];
if($value == "$username")
{
$result = mysqli_query($con, "SELECT * FROM User_info WHERE username ='$username'");
$row = mysqli_fetch_array($result);
$value = $row['password'];
if($value == "$password")
{
$sql=("UPDATE user_check SET user = '1', name = '$username'");
header( 'Location: feed.php' ) ;
}
else
{
header( 'Location: social.php' ) ;
}
}
else
{
header( 'Location: social.php' ) ;
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Which gets the form data from the previous page i do not know why this is happening and i have tryed changing the php to this :
$result = mysqli_query($con, "SELECT username FROM User_info");
$row = mysqli_fetch_array($result);
if($row == "$username")
Yet that doesnt work either any suggestions?
the problem is that, after your first query, to get the info from db, you are taking only the first row of the table,
$row = mysqli_fetch_array($result);
then comparing it with the submitted username, that's why you can't login with any other username, the solution is to add a WHERE clause to the first query,
$result = mysqli_query($con, "SELECT * FROM User_info WHERE username ='".$username."'");
then compare passwords that would be easier, but still, there are better ways to do the authentication. but for your example this should do.
Modify your code as below:
<?PHP
//Create the connection…
//("where the database is", 'Database login' , 'database password' , "Database name")
$con=mysqli_connect("", 'root', 'root', "Social");
//Check our connection…
if (mysqli_connect_errno($con))
{
echo " Sorry Mate";
}
$username = $_POST['username'];
$password = $_POST['pawd'];
$result = mysqli_query($con, "SELECT count(*) as count FROM User_info WHERE username ='$username' and password='$password'");
while( $rows = mysqli_fetch_array($con, $result) )
{ //Check for SQL INJECTION
if( $rows['count'] == 1 )
{
//$sql=("UPDATE user_check SET user = '1', name = '$username'");
//header( 'Location: feed.php' ) ;
//Other Operations
}
else
{
header( 'Location: social.php' ) ;
}
}
mysqli_close($con);
?>

Problem with blank submitted values and returned mysql query

<?php
$link = mysql_connect('127.0.0.1', 'ilhan', 'password123');
if(!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("metu", $link);
mysql_set_charset('utf8',$link);
if(isset($_POST["email"])) // AND strlen($_POST["email"])>1 solves the problem
// but I didn't get why the page is redirected...
{
$email = mysql_real_escape_string($_POST["email"]);
$password = mysql_real_escape_string($_POST["password"]);
$result = mysql_query("SELECT password, id FROM users WHERE email = '$email'");
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
$row = mysql_fetch_assoc($result);
if($row['password'] == $password)
{
$_SESSION['valid_user'] = $row['id'];
mysql_close($link);
header("Location: http://www.example.com");
}
else $login = false;
mysql_close($link);
}
else $login = false;
?>
Do you think that the page will be redirected if the user submits a blank email and blank password? It shouldn't but the page is redirected. Why is that? Bug?
I've overlooked the issue at first.
here it is:
if($row['password'] == $password)
empty $row['password'] is equal to empty $password. evaluated to true
here is what I'd do it
<?php
include 'db.php';
if(isset($_POST["email"]))
{
$sql = "SELECT id FROM users WHERE email='%s' AND password='%s'";
$id = dbGetOne($sql,$_POST["email"],MD5($_POST["email"].$_POST["password"]));
if($id)
{
$_SESSION['valid_user'] = $row['id'];
header("Location: http://www.example.com");
exit;
}
}
Use mysql_num_rows function to find then umber of rows returned. mysql_query will return FALSE on error but in your case, your SQL is still a valid SQL if email is blank. It will just return an empty result set.
if(isset($_POST["email"]))
// AND strlen($_POST["email"])>1 solves the problem
// but I didn't get why the page is redirected...
if $_POST["email"] is empty string -> isset will return true
EDIT: add if ( isset($_POST["email"]) && isset ($_POST["password"]) ) to avoid empty passwords and make sure that $row is not empty when `if($row['password'] == $password)'

Categories