0

Im trying to create a login page. Connection is successful but query is not fetching the required result. login page sends data through post method to action_page.php.

Action_page.php

<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "MyDB";

$con = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$uname = $_POST['uname'];
$pass = $_POST['psw'];
$sql = "SELECT * FROM Users WHERE uname=".$uname." AND pass=".$pass;
echo "<br/>$sql<br/>";

//$result = $con->query($sql);

echo var_dump($con->query($sql));

$con->close();

This is my database.?>

could someone please help.!

Wisam Ahmed
  • 145
  • 1
  • 1
  • 13
  • 3
    I'm not a PHP expert, but immediately I can see the problem. You are building your query string using a raw concatenation. While this is bad in so many other ways, the current problem is that your strings are not properly being escaped with single quotes so that MySQL can recognize them. The answer is to use prepared statements here. – Tim Biegeleisen Dec 07 '17 at 06:08
  • is query giving result from db? – K.B Dec 07 '17 at 06:08

3 Answers3

2
You can use single quote for the inserted variable inside double quote :)

$sql = "SELECT * FROM Users WHERE uname='$uname' AND pass='$pass'";
not_null
  • 111
  • 10
1

update from

$sql = "SELECT * FROM Users WHERE uname=".$uname." AND pass=".$pass;

to

$sql = "SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'";
K.B
  • 885
  • 5
  • 10
1

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development, as it was deprecated in PHP 5.5.0 and was removed in PHP 7.

Example Your code Comparing with three MySQL APIs

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = $result->fetch_assoc();
echo htmlentities($row['uname']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['uname']);

// mysql
$c = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['uname']);
?>

check link

Abhijit Jagtap
  • 2,740
  • 2
  • 29
  • 43