0

I connected my database to php, and made sure the connection was established. Even with the connection, and double-checking all the syntaxes for my inserts, it won't work (It won't do any insert of value in my database).

Here is my code:

Backend side:

<?php
include "dbconnector.php";
include "DB_functions.php";

function setcategories($uid){
   $categories = getcategroies();;
    for ($i = 0; $i < sizeof($categories); $i++) {
        if (isset($_POST[$categories[$i]])){
            $cid = getcategorieid($_POST[$categories[$i]]);
            $query = "INSERT INTO  categorytouser (userID, categoryID) VALUES (?,?)";
            $stmt = $mysqli->prepare($query);
            $stmt->bind_param("ss", $uid,$cid );
            $stmt->execute();

        }
    }
}

$error = $message =  '';
$adminkey = 123456;
// Wurden Daten mit "POST" gesendet?

if($_SERVER['REQUEST_METHOD'] == "POST"){
    // Ausgabe des gesamten $_POST Arrays
    echo "<pre>";
    print_r($_POST);
    echo "</pre>";

    if(isset($_POST['username']) && !empty(trim($_POST['username'])) && strlen(trim($_POST['username'])) <= 30){
        $username = trim($_POST['username']);
 
        if(!preg_match("/(?=.*[a-z])(?=.*[A-Z])[a-zA-Z]{6,}/", $username)){
            $error .= "Der Benutzername entspricht nicht dem geforderten Format.<br />";
        }
    } else {
        $error .= "Geben Sie bitte einen korrekten Benutzernamen ein.<br />";
    }

    if(isset($_POST['password']) && !empty(trim($_POST['password']))){
        $password = trim($_POST['password']);
        $password = password_hash($password, PASSWORD_BCRYPT);

        if(!preg_match("/(?=^.{8,}$)((?=.*\d+)(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/", $password)){
            $error .= "Das Passwort entspricht nicht dem geforderten Format.<br />";
        }
    } else {
        // Ausgabe Fehlermeldung
        $error .= "Geben Sie bitte einen korrekten Nachnamen ein.<br />";
    }

    if(isset($_POST['admin-password']) && $_POST['admin-password'] == $adminkey){
        $admin = 1;
    } else {
        $admin = 0;
        $error ="password is false";
    }
    // wenn kein Fehler vorhanden ist, schreiben der Daten in die Datenbank
    if(empty($error)){

        $stmt = $mysqli->prepare("INSERT INTO users (Name, password, Rights) VALUES (?,?,?)");
        $stmt->bind_param('ssi', $username, $password, $admin);
        $stmt->execute();

        if($stmt===false){
            $error .= 'prepare() failed '. $mysqli->error . '<br />';
        }
        // parameter an query binden
        if(!$stmt->bind_param('sss',$username, $password, $admin)){
            $error .= 'bind_param() failed '. $mysqli->error . '<br />';
        }

        // query ausführen
        if(!$stmt->execute()){
            $error .= 'execute() failed '. $mysqli->error . '<br />';
        }
        // kein Fehler!
        if(empty($error)){
            $stmt->execute();
            $message .= "Die Daten wurden erfolgreich in die Datenbank geschrieben<br/ >";
            // verbindung schliessen
            $mysqli->close();
            $id=getuserid($username);
            setcategories($id);

        }
    }
}

?>

Frontend side:

<?php
include("../common/Backend/DB/POST_createuser.php");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../css/styles.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <title>Registrierung</title>
</head>
<body>
<form action="Register.php" method="post">
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <div class="panel panel-login">
                    <div class="panel-heading">
                        <div class="row">
                            <div class="col-xs-6">
                                <a href="login.php" id="login-form-link">Login</a>
                            </div>
                            <div class="col-xs-6">
                                <a href="Register.php" class="active" id="register-form-link">Register</a>
                            </div>
                        </div>
                        <hr>
                    </div>
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-lg-12">
                                <form id="register-form" action="Register.php" method="post" role="form" style="display: none;">
                                    <div class="form-group">
                                        <input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
                                    </div>
                                    <div class="form-group">
                                        <input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
                                    </div>
                                    <div class="form-group">
                                        <input type="password" name="confirm-password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password">
                                    </div>
                                    <div class="form-group">
                                        <input type="administrator" name="admin-password" id="admin-password" tabindex="2" class="form-control" placeholder="Admin Registration Key">
                                    </div>
                                    <div class="form-group">
                                        <div class="row">
                                            <div class="col-sm-6 col-sm-offset-3">
                                                <input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
                                            </div>
                                            <div class="col-sm-6 col-sm-offset-3">
                                                <p>In order to register as an Admin, you need to know the registration key</p>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
</body>
</html>

Everything works, the files are connected together.

Image of the proof that everything works

Thanks to the people that could help me out!

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sdev
  • 73
  • 11
  • 1
    Help us narrow it down. What does the insert call return? Does it even get that far? No warnings or errors? – ficuscr Feb 23 '22 at 07:19
  • Btw, you're checking the password format (you `preg_match()`) _after_ you've hashed it, so you're just verifying the hash, not the password. – M. Eriksson Feb 23 '22 at 07:23
  • You should also configure [mysqli to throw exceptions](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) instead of manually checking for errors. And logic wise, it makes no sense to have `if ($stmt === false)` and echo that "prepared failed" after you've tried to bind params and execute the statement. If the prepare fails, then you'll get errors when trying to bind and execute it (before that check). There's also no need to try again with the exact same statement and params if it failed the first time. You actually have `execute()` three times!? – M. Eriksson Feb 23 '22 at 07:29
  • @ficuscr Not any call return, that's the problem, everything seems to be working. I even get the echo that the connection was succesfully made beetween php and my database. – Sdev Feb 23 '22 at 07:32
  • @M.Eriksson Thanks! I'll try these things right now. – Sdev Feb 23 '22 at 07:33
  • 1
    Also, in your function `setcategories()`, there are no variable `$mysqli` defined in that scope _plus_ that you close the mysqli connection you've previously used before you even call that function. You should take a step back and start over. Do one thing at the time and don't continue to the next step until you've gotten the first working (and understand how it works) – M. Eriksson Feb 23 '22 at 07:33
  • @M.Eriksson I found out that the var $mysqli is recognised from my include, PHPStorm just doesn't recognise it and shows an error, otherwise I couldn't even have any connection proof with the database. – Sdev Feb 23 '22 at 07:58
  • It will still be undefined inside your `setcategories()`-function. Variables are only accessible within the scope they're defined. – M. Eriksson Feb 23 '22 at 08:49
  • @M.Eriksson okay, I'll just define it as a function that I create to connect the DB – Sdev Feb 23 '22 at 08:53
  • 1
    Just make sure it won't create a new connection every time you call it. A better way would be to just pass the connection to the function as an argument – M. Eriksson Feb 23 '22 at 08:55
  • Ok, I made all the changes, no errors, nothing. It just puts nothing in the Database... – Sdev Feb 23 '22 at 09:10

0 Answers0