1

this is my login.php file

<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>  
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
    Name : <input type="text" name="name"><br/>
    Password : <input type = "text" name="password"><br/>
    <input type="submit" name="login" value="Log In">   
    </form>

    <?php
    $name=$password="" ;
        if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
            $name = testInput($_POST["name"]);
            $password = testInput($_POST["password"]);
        }//if ends here

        //testInput function
        function testInput($data){
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
        }//testInput ends here


        if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){

        //echo "Name ".$_POST["name"];

        if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")){            
            if($result->num_rows > 1){
            echo "you are logged in";
                while ($row = $result->fetch_assoc()){
                    echo "Name ".$row["name"]."-Password ".$row["password"];
                }//while loop ends here  
            }//if ends here


            /* free result set */
            $result->close();
        }       
        else{
            print "Wrong Credentials "."<br>";
            die(mysqli_error($conn));
        }
        }       
        //close connection
        $conn->close();
    ?>
</body>
</html>

One problem is that my query
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")) returns column names as one row. I don not know whether it is ok ?
The other thing whether I put wrong name or password or correct , in both cases I do not get any output. What I am doing wrong here ?

And if you can please tell me how to write a mysqli query in php with correct format with a comprehensive example . I searched on google but there are different ways so I am confused specially when column names and variables come in the query.

9
  • 3
    if($result->num_rows > 1){ means that you're looking for 2 or more results from your query.
    – andrewsi
    Jul 6, 2015 at 13:59
  • You have checked that the database isn't containing a row with the values of name and password? Jul 6, 2015 at 14:01
  • @andrewsi as I stated in my question that my query returns column names as one row and I dont want to compare my values with column names. That's why I am checking for >1. Jul 6, 2015 at 14:03
  • Dont use mysqli_query use prepare and execute. Or atleast use the escape.
    – chris85
    Jul 6, 2015 at 14:03
  • 1
    @Adamnick - it's returning one row. So having your check look for num_rows > 1 will not work. You're using fetch_assoc to load that single row into an associative array, for which the keys are the column names, and the values are the entries from the database.
    – andrewsi
    Jul 6, 2015 at 14:18

4 Answers 4

1

Your test_input function is weak/unsafe, also, mysql_query is depricated, use mysqli and prepared statements as explained here: http://php.net/manual/en/mysqli.prepare.php

Furthermore, I included a section of code I use for my login system (bit more sophisticated using salts etc, you should be able to compile it in a piece of script suitable for you.

//get salt for username (also check if username exists)
        $stmtfc =  $mysqli->stmt_init();
        $prep_login_quer = "SELECT salt,hash,lastlogin FROM users WHERE name=? LIMIT 1";
        $stmtfc->prepare($prep_login_quer);
        $stmtfc->bind_param("s", $username);
        $stmtfc->execute() or die("prep_login_quer error: ".$mysqli->error);
        $stmtfc->store_result();
        if ($stmtfc->num_rows() == 1) {
            $stmtfc->bind_result($salt,$hash,$lastlogin);
            $stmtfc->fetch(); //get salt
            $stmtfc->free_result();
            $stmtfc->close();
1
  • I will surely test your code and let you know :) Thanks. Jul 6, 2015 at 14:48
0

I don't know what do you mean but thats how i query mysqli

$query = mysqli_query($db, "SELECT * FROM users WHERE name='$name' AND password='$password'");

if($query && mysqli_affected_rows($db) >= 1) { //If query was successfull and it has 1 or more than 1 result 
echo 'Query Success!';
//and this is how i fetch rows
while($rows = mysqli_fetch_assoc($query)) {
   echo $rows['name'] . '<br />' ;
}

} else {
echo 'Query Failed!';
}

i think thats what you mean

EDIT:

<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>  
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
    Name : <input type="text" name="name"><br/>
    Password : <input type = "text" name="password"><br/>
    <input type="submit" name="login" value="Log In">   
    </form>

    <?php
    $name = null ;
    $password= null ;
        if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
            $name = mysqli_real_escape_string($conn, $_POST["name"]); //I updated that because your variables are not safe
            $password = mysqli_real_escape_string($conn, $_POST["password"]);
        }//if ends here

        //testInput function
        function testInput($data){
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
        }//testInput ends here


        if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){

        if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='{$name}' and password='{$password}'")){            

            print "rows are ".mysqli_num_rows($result)"<br>";//number of rows

            if($result && mysqli_affected_rows($conn) >= 1){//If query was successfull and it has 1 or more than 1 result
            echo "you are logged in<br>";
                while ($row = mysqli_fetch_assoc($result)){
                    echo "Name ".$row["name"]."-Password ".$row["password"];
                }//while loop ends here  
            }//if ends here


            /* free result set */
            mysqli_free_result($result);
        }       
        else{
            print "Wrong Credentials "."<br>";
            die(mysqli_error($conn));
        }
        }       
        //close connection
        mysqli_close($conn);
    ?>
</body>
</html>
2
  • I have updated according to your link but I only get one rows and that row is column names . :/ Jul 6, 2015 at 15:02
  • i think that problem occurs because you're mixing procedural style with object oriented programming btw i updated your code see if that works (i edited my answer)
    – Iatrarchy
    Jul 24, 2015 at 13:56
0

try to change this query

$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")

to

$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password' limit 1")

then you will get only one row , and try to change

$row = $result->fetch_assoc()

to

$row = $result->mysqli_fetch_row()

then you can display the results by colomn number instead of colomn name

4
  • Don't forget to point out that the following if statement should be changed to if($result->num_rows == 1){ - but that doesn't explain why OP is receiving the column names in the results. Jul 6, 2015 at 14:10
  • I got this error Fatal error: Call to undefined method mysqli_result::mysql_fetch_row() in C:\xampp\htdocs\facebook\login.php on line 34 Jul 6, 2015 at 14:17
  • mysql_fetch_row is part of the mysql_ library - it's nothing to do with mysqli
    – andrewsi
    Jul 6, 2015 at 14:19
  • what I am supposed to do now ? @andrewsi Jul 6, 2015 at 14:45
0
<?php 
  mysql_connect("abc.com","user","password");
  mysql_select_db("database name"); 
  $query1="select * from table_name"; 
  $exe1= mysql_query($query1); 
  $row= mysql_fetch_assoc($exe1); 
  if($row["email"]==$_POST["email"] && $row["[password"]==$_POST["password"]) { 
    echo "Login successfully"; 
  } else {
    echo "error in login"; 
  } 
?>

enter your column name in row["email"] and $row["password"]

2
  • <?php mysql_connect("abc.com","user","password"); mysql_select_db("database name"); $query1="select * from table_name"; $exe1= mysql_query($query1); $row= mysql_fetch_assoc($exe1); if($row["email"]==$_POST["email"] && $row["[password"]==$_POST["password"]) { echo "Login successfully"; } else { echo "error in login"; } ?> Jul 6, 2015 at 14:37
  • Indent your code 4 spaces for it to show up in an answer. Or, paste your code, select it, and press the { } button in the toolbox.
    – Tim Lewis
    Jul 6, 2015 at 14:49

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.