0

I'm very new to PHP and coding, and am trying to learn - but I'm stuck and was hoping someone could point out what's wrong -

My code is showing text "Failure" as soon as I open my page. My goal is to have "Failure" only show when the user inputs information and it fails to connect to the database.

I'm using WAMP and my database server is in MySQL. Additionally, when I click "Register" I'm not getting any results in my database - and no error message to indicate why.

php

<?php
require('connect.php');


$username = @$_POST['username'];
$password = @$_POST['password'];
$repass = @$_POST['repassword'];
$Email = @$_POST['email'];


if(isset($_POST['submit']))     

    {
    if($query = mysqli_query("INSERT INTO users (`id`, `username`, `password`, `email`) VALUES ('', '".$username."', '".$password."', '".$Email."')"))

        echo "Success";
}else{
    echo "Failure";
    }   
?>

database

<?php

$connect = mysqli_connect("localhost", "root", "") or die("Couldn't connect to server");
    mysqli_select_db($connect, "php_forum") or die("Couldn't connect to database");


?>

Please help! Let me know if I have not explained what is occurring well enough

MrMonk
  • 1
  • When you initially call that script then mast likely no submit button has been pushed, or has it? If not, then sure, you will enter the `else` branch. If a button _has_ been pushed, then you need to check why it is not set in the `$_POST` variable. That depends on your form implementation, which you did not show us... – arkascha May 24 '18 at 19:08
  • And a side remark: one does _never_ store a user password inside a database on the server side. _Never_. Instead one stores a _hash_ of the password using a _good_ hashing algorithm. Then, at authentication time one again hashes the provided password and compares the two hashes for equality. That way one does not compromise ones users passwords even if the own server has been broken into. – arkascha May 24 '18 at 19:10

3 Answers3

1

To answer your specific question:

The reason you see "Failure" when visiting the page is this:

echo "Failure";

Which gets run when isset($_POST['submit']) is false.

You could update your code to look like this and you will be closer, but will still have to deal with your other registration related problems.

if (isset($_POST['submit'])) {
    if ($query = mysqli_query("INSERT INTO users (`id`, `username`, `password`, `email`) VALUES ('', '" . $username . "', '" . $password . "', '" . $Email . "')")) {
        echo "Success";
    } else {
        echo "Failure";
    }
} 
Andrew
  • 13,934
  • 8
  • 78
  • 93
0

General Advice

  • Remove your @. The ampersand symbol suppresses error messages. It's a bad idea to use it 999/1000 times.
  • Remove your ?> unless you're actually posting out non-PHP data after this point (such as HTML)
  • Only store the hashes of passwords by using PHP password_hash. NEVER store plaintext passwords in your database. Ever. Nope, not even on testing. (Ok, How do I do this?)
  • Use PHP Prepared Statements to protect yourself from SQL Injection attacks and maintaining Best Practise. (How? )
  • NEVER insert unqualified user submitted data into your Database. This can only be acceptable (but still, not wise imho) if you're using Prepared Statements. ALWAYS check the data given in any HTML <form> is valid (Rough guide to Prepard Statements).
  • Use PHP's in depth and extremely helpful Error Logging system, and use it to give you feedback on your scripts.
  • Do NOT get into the habit of outputting detailed errors to the browser (such as with die() statements).
  • Use a proper IDE which can help you Enormously with syntax and coding styles.
  • Check that your HTML form is POSTing data rather than GETting data. (There are LOTS of questions on Stack Overflow about possible errors in this arena).
  • AUTO_INCREMENT MySQL column values (id) can be ignored in the PHP SQL code, they will be inserted by MySQL all by itself.
  • Understand the fundamentals of how PHP operates; how it interacts with your HTML and the logical process order of how things happen.

Good ways to learn:


My Personal View

Your code is terrible, but that's ok. What you need to be is consistent. Even, consistently terrible, is better than being abstractly terrible.

You need to form your if statements consistently. Sometimes they have brackets {...} and sometimes they don't. This makes it harder to read your code correctly.

I personally think that isset is a terrible function to use. I also think you should get into a habit of using (and checking) a CSRF token.


Your code:

Please forgive me not putting the extensive time and effort into applying Prepared Statements to this codeblock. It will obscure the intended changes for the OP as they are not well used to Prepared Statements

<?php
require('connect.php');

$username = $_POST['username'];
$password = $_POST['password'];
$repass = $_POST['repassword'];
$Email = $_POST['email'];

if($_POST['CSRF_token'] == $_SESSION['token_value'])     
    {
    /***
     * Check Password values are equal.
     ***/
    if($password == $repass){
        $pwd = password_hash($password,PASSWORD_DEFAULT); 
    }
    else {
        echo "passwords do not match! Nothing saved!";
        die();
    }
    /***
     * Likewise you can also check the Emal is a valid format, etc. etc.
     ***/

    /***
     * Try and insert using procedural MySQLi. 
     * Note if statement brackets.
     ***/
    if($query = mysqli_query("INSERT INTO users ( `username`, `password`, `email`) VALUES ( '".$username."', '".$pwd."', '".$Email."')")){
        echo "Success"; //only echoed if the INSERT succeeds
    }
    else{
        /***
         * Only echoed if the insert failed 
         * AND the form WAS submitted. 
         ***/
        echo "Failure"; 
    }   
} // close your outer if block. 
Community
  • 1
  • 1
Martin
  • 19,815
  • 6
  • 53
  • 104
-1

Your connection is missing parameters, should be $connect = mysqli_connect("HostName","UserName","password","DBName") or die("Some error occurred during connection " . mysqli_error($con)); this will include error checking.

Why do you have the @ symbol in front of your variable and the periods before all the variable in you query statement (may be a silly question and if so sorry)?

deanksa
  • 1
  • 4
  • There is nothing wrong with the code the OP writes. The fourth parameter is optional and is given on the next line of code – Martin May 24 '18 at 19:37
  • Apologies, was under the impression all 4 parameters where mandatory. – deanksa May 25 '18 at 12:49