-3

i have problem with my foreach... Can you please help me repair this problem ? Thanks guy :)

(It will be login)

Warning: Invalid argument supplied for foreach() on line 33

        if(isset($_POST["UserName"]) AND isset($_POST["Password"])){
        $UserName = $_POST["UserName"];
        $Password = $_POST["Password"];
        $Password = hash("SHA256", $_POST["Password"]);


            $sql = "SELECT UserName FROM Login WHERE UserName=$UserName";
    foreach($db->query($sql) as $data) {
                if ( $_POST['UserName'] == $data["UserName"] && $_POST['Password'] == $data["Password"] ){
                    header("Location: index.php");
        }else{
        $cnt = 1;
      }
     }      
                if(!empty($cnt)){
        echo "Špatné jméno nebo heslo!";
      }


                if(!isset($UserName)){
                        $_SESSION["Time"] = 36000; 
            $_SESSION["LogedIn"] = 1;

    }      
                }   

        }
  }
  }
Jan Kočvara
  • 81
  • 10
  • 5
    1) you should look up prepared statements / parameterised queries. 2) `$UserName` needs quoted as it's a string 3) Look at the built in PHP [password API](http://php.net/password). – Jonnix Sep 28 '15 at 13:41
  • 1
    @JonStirling This is the correct answer. – elixenide Sep 28 '15 at 13:42
  • 2
    4) You don't request `Password` in your SQL, so that condition is never going to pass. 5) Try not to mix and match `&&` and `AND`. 6) Sort out your indentation. – Jonnix Sep 28 '15 at 13:42
  • 3
    Your SQL query is probably resulting in an error. Probably because the string value has no quotes around it. (Being wide open to SQL injection certainly doesn't help either, since technically you could be executing *any* code supplied by the user.) Never *assume* that a SQL query will succeed. Always check for errors before proceeding. – David Sep 28 '15 at 13:44

1 Answers1

0

Warning: Invalid argument supplied for foreach() that mean query() fail and did not return an array.

There some errors, use prepared statements insted of put raw values at query, text/string type need quotes, in your query return the password not only the username if not a key named password never will defined an returned array.

correct code

$sql = "SELECT UserName, Password FROM Login WHERE UserName = ?";
$stmt = $db->prepared($sql);
if(!$stmt->execute(array($UserName)){
   print_r($stmt->errorInfo());
   exit;
}

$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($items as $data) {
rray
  • 2,518
  • 1
  • 28
  • 38