1

So, I am trying to validate whether username and email entered by a user in an html form are correct according to Database

I have a database called testing and a table called info which has two fields: name and email.

this is the code

<html>
<body>

<form action="conn.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>   
<input type="submit">
</form>

</body>
</html>


    <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="testing";
$name=$_POST['name'];
$mail=$_POST['email'];
// Create connection
$conn1 = new mysqli($servername, $username, $password, $dbname);
$query='select email from info where name= "$name"';
$results = mysqli_query($conn1,$query);
$row= mysqli_fetch_assoc($results);
echo $row["email"];
$email=$row["email"];
if($mail==$email){
    echo " correct values";
} 
else 
    echo " incorrect";
//echo $name, $email;
// Check connection
//if ($conn1->connect_error) {
//    die("Connection failed: " . $conn1->connect_error);
//} 
//echo "Connected successfully";
$conn1->close();
?>

but the result is always incorrect. The values that i enter in the text boxes match the values in the database.

Tom Regner
  • 6,856
  • 4
  • 32
  • 47
  • First: Don't try to interpolate user-input directly into sql queries, use placeholders ('?'), youre open to SQL-Injection attacks otherwise. If you had used placeholders, the query would actually have worked -- as your code stands you select for a literal '$name' as name, NOT the entered name. – Tom Regner Feb 11 '17 at 07:07

2 Answers2

1

You should use placeholders, the code would be something like this:

$query = 'SELECT emal FROM info WHERE name = ?';
$stmt  = mysqli_stmt_prepare($conn1, $query);
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);
$results = mysqli_stmt_get_result($stmt);

For better readable code, read up on the object-oriented mysqli-interface, or better yet use PDO.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Tom Regner
  • 6,856
  • 4
  • 32
  • 47
-1

alternatively you can use string concatenation like

Update this line

$query='select email from info where name= "$name"'; 

with

$query='select email from info where name= "'.$name.'" '; 

or with

$query="select email from info where name= '".$name."' "; 
Kunal
  • 219
  • 2
  • 9