Reviewing your code more closely, you can see that here:
if (!$result . mysqli_error()) {
you make an incorrect evaluation. It's like you do this:
$result=TRUE;
$error="Hubo un error";
if (!$result.$error){
die ("Query failed");
}
The code will always enter the if
because you're asking if the concatenation !$result . mysqli_error()
is not FALSE
. And it never will be, nor should this happen:
$result=FALSE;
$error="Hubo un error";
if (!$result.$error){
die ("Query failed");
}
Here I would also enter the if
.
Then, taking into account that $result
would store the result of mysqli_query
and that this would be FALSE
if the query failed, you can write the code like this:
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$connection = mysqli_connect('localhost', 'root', '', 'cs base de datos');
if ($connection) {
echo "We are connected";
} else{
die("failed");
}
$query = "INSERT INTO usuarios (username, password) ";
$query .= "VALUES ('$username', '$password')";
$result = mysqli_query($connection, $query);
if (!$result) {
die('Query failed '.mysqli_error());
} else {
echo "Se insertaron: ".mysqli_affected_rows($connection). " registros";
}
}
?>
That way, when it fails, it will tell you what the error was, because you are evaluating only the variable $result
and not a concatenation of it.
If it still does not work, comment on the error that is printed on the screen, next to Query failed
.
Note that I have used mysqli_affected_rows
to indicate the number of records inserted, when the query works. If this function does not fall within the scope of your course, you can remove it.
NOTE:
Once the present error is corrected, consider shielding your code
against the very serious security risk called SQL Injection, a
through which a malicious user could take control not
only from your database, but from the entire system . If this type of solution is acceptable for your case (since you have commented that it is a course), you can tell me in comment and I show you how to shield the code.