-1

I am trying to write a program for my test lab with windows 2012 + MySQL + IIS + PHP, my program read the database, but when I am trying to write the data to the database, it shows "Array ( [id] => 0 )", that means my program does not writing data to the database, what is the problem ? I am a beginer writing program, please help me ? My code is as under :

<?php

session_start();

error_reporting(E_ALL & ~E_NOTICE);

// Connect to Database

$link = mysqli_connect("localhost", "root", "password", "admin");

// Connection Status

if ($link->connect_error) {

    die ("Connection Failed : " . $link->connect_error);
}

if ($_POST['submit']) {

    if (!$_POST['email'])
        $error .= "<br />Bitte trage deine Email Addresse ein !";

    else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
        $error .= "<br />Bitte eine korrekte email Address ein !";

    if (!$_POST['password'])
        $error .= "<br />Bitte trage dein Passwort ein !";

    else {
        if (strlen($_POST['password']) < 8)
            $error .= "<br />Bitte trage ein längeres Password ein !";

        if (!preg_match('`[A-Z]`', $_POST['password']))
            $error .= "<br />Bitte nutze ein Großbuchstaben password ein !";

    }

    if (isset($error))
        echo "Es gab fehler in deinem Login Details : " . $error;

    else {

        $query = "SELECT * FROM `benutzer` WHERE email ='" . mysqli_real_escape_string($link, $_POST['email']) . "'";

        $result = mysqli_query($link, $query);

        $results = mysqli_num_rows($result);

        if ($results) echo "Die eMailaddresse ist bereits vergeben. <br />Möchtest do dich einloggen ?";

            $query = "INSERT INTO benutzer (email, password) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . md5(md5($_POST['email']) . $_POST['password']) . "')";

            mysqli_query($link, $query);

            echo "<br />Du hast dich erfolgreich registriert ! ";

            $_SESSION['id'] = mysqli_insert_id($link);

            print_r($_SESSION); 


    }

}

?>



<form method="post">

    <input type="email" name="email" id="email" id="email" />
    <input type="password" name="password" />
    <input type="submit" name="submit" value="Einlogen" />

</form>
Martin
  • 22,212
  • 11
  • 70
  • 132
TSahoo
  • 1
  • 2
    Your if/else statements are a mess. I would suggest using braces `{ }` on them all. Odds are, you will discover a syntax error that once fixed, will fix your problem. At the very least, if you edit your cleaned up code into your question, it will make it a lot easier for us to see what is going on. – amflare Apr 25 '16 at 21:36
  • also insert "echo mysqli_error($link);" after your mysqli_query call – strangeqargo Apr 25 '16 at 21:38
  • **WARNING**: When using `mysqli` you should be using parameterized queries and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you will create severe [SQL injection bugs](http://bobby-tables.com/) if you make a simple mistake. – tadman Apr 25 '16 at 21:38

3 Answers3

0

There is a huge amount you should be doing to mitigate and secure your database connectivity and you should be developing current best practise for usernames/passwords.

  • MySQLi real escape string is not enough to protect you from SQL injection.

  • MD5 is an unsuitable hashing mechanism for passwords, you should be using PHP password_hash. Use it.

  • use MySQLi_error($link) to feedback what's wrong with your SQL query:

So:

 mysqli_query($link, $query) or die("line ".__LINE__." :".mysqli_error($link));

One big improvement you can make is to use MySQLi Prepared statements (natively actually more secure than the more popular PDO, as they use fully prepared statements from the outset)

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132
0

You can check if the program executed the INSERT query successfully by checking if mysqli_query returns true.

Also mysqli_insert_id will return 0 at the first time then start counting though it could make problems in some databases. You could get the id from mysqli_num_rows() - 1

Replace this code after the if($results):

if(mysqli_query($link, $query))
{
    echo "<br />Du hast dich erfolgreich registriert ! ";

    $query = "SELECT * FROM `benutzer`";

    $result = mysqli_query($link, $query);

    $results = mysqli_num_rows($result);

    $_SESSION['id'] = $results-1;

    print_r($_SESSION);
}
else
    echo "Error inserting data!"; 
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ofir
  • 141
  • 14
0

Exceptions are your friend, and can easily avoid the kind of nasty and hard to follow nested if blocks you have going on here. It should be easy to read your script and follow the flow of logic.

Here's quick example with exceptions and functions encapsulating areas of interest.

function dbConnect()
{
   $link = mysqli_connect("localhost", "root", "System@2012", "admin");
   if($link->connect_error)
   {
       throw new Exception($link->connect_error);
   }
}

function checkRequiredValues()
{
     // initialize $error before beginning.
     $error = '';

     // Check email address
     if (empty($_POST['email'])) 
     {
          $error .= "<br />Bitte trage deine Email Addresse ein !";
     }
     else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
     {
          $error .= "<br />Bitte eine korrekte email Address ein !";
     }

     // Check password. 
     if (empty($_POST['password']))
     {
         $error .= "<br />Bitte trage dein Passwort ein !";
     }
     else if (strlen($_POST['password']) < 8)
     {
        $error .= "<br />Bitte trage ein längeres Password ein !";
     }
     else if (!preg_match('`[A-Z]`', $_POST['password']))
     {
        $error .= "<br />Bitte nutze ein Großbuchstaben password ein !";
     }
     if (isset($error))
     {
      throw new Exception("Es gab fehler in deinem Login Details : " . $error);
    }
}




// use !empty here to avoid a warning if post['submit'] is not set
if(!empty($_POST['submit']))
{
    try 
    {
        checkRequiredValues();
        // Do this second.  There is no need to establish a DB 
        // connection if we won't be using it. 
        dbConnect();
        doUpdate();
    }
    catch(\Exception $e)
    {
        $e->getMessage(); 
    }
}

I'll leave writing the doUpdate function to you. Note that what the other poster said about using bound parameters is correct.

cmason
  • 51
  • 2