Insert to table always failure - php

Its a simple registration with username and password, but when I try to insert it to the database it always fails and I don't know why, can someone help me with this?
include "db.php";
if (isset($_POST['submit']))
{
$username= $_POST['leguser'] ;
$password= $_POST['legpass'] ;
$pwhash = password_hash($password, PASSWORD_DEFAULT) ;
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
echo var_dump ($username);
echo var_dump ($password);
echo var_dump ($pwhash);
$sql = "SELECT * FROM tbl_users WHERE fld_username = '$username'";
$result = $conn->query($sql);
if ($result->num_rows === 1) {
echo "<script>alert('Username already used!');</script>"; }
else
{
$q = "INSERT INTO `tbl_users` (`fld_username`) VALUES ('$username')";
$result = mysql_query($q);
if ($result) {
echo 'success';
} else {
echo 'failure';
}
}
This is the code of the database connection (db.php)
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'rsi_db';
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
By the way I only want to input only one data on the database which is the username, for me not to get complicated with every data that I want to put in the future.

Related

My PHP login system still Logging in even if the password or username is incorrect

Still loggin in even if the username and password is incorrect and also logins even if the value is null
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if ($_POST) {
$uname = $_POST ["username"];
$pass = $_POST ["password"];
$sql = "SELECT * FROM users WHERE username = '$uname' AND password = '$pass' LIMIT 1 ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
include("graph.php");
} else {
echo "Incorrect";
}
}
?>
First of all and very important it that you are open to SQL Injection attack, so you should use prepared statements, here is how should use your code, but instead of echo "Incorrect"; you should render different answer for each case:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if (isset($_POST["username"]) && isset($_POST["password"])) { // Check if you have posted data via POST
$uname = $_POST["username"];
$pass = $_POST["password"];
$sql = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1 ";
if($stmt = $conn->prepare($sql)) { // Check for MySQL errors
$stmt->bind_param('ss', $uname, $pass);
if ($stmt->execute()) {
$stmt->close();
include("graph.php");
} else { // There is a problem with your SELECT // bind params
echo "Incorrect";
}
} else { // You should handle mysql errors here
echo "Incorrect";
}
} else { // You don't have POST data
echo "Incorrect";
}
?>
Prepared statements
Like #Kuya notice you have and many other problems, there is a lot of tutorials in Google about implementation of login system.
You must check the post request with isset() in php like this :
<?php
if (isset($_POST["username"] && isset($_POST["password"]))) {
//..... Your code here
}else {
echo "Incorrect password or username";
}
?>

Mysqli_num_row not generating the database row correctly

I am trying to get the row of my email in my database and I use the query so I can validate the email in my database and I used the code
if (isset($_POST['submit'])) {
$num = 1;
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'user_managment';
$connection = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
$query = mysqli_query($connection, "SELECT count(id) FROM users WHERE email = 'user#gmail.com'");
$result = mysqli_num_rows($query) == $num;
if ($result){
echo 'Yes';
}else{
echo 'No';
}
}
my database is here and I only have an email(alex#gmail.com)
but I do the notice these still echo out 'yes' whenever I insert email that ain't in my DB
That's because you do COUNT(*), this will always result in a single record.
A better solution would be:
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT email FROM users WHERE email=?");
$stmt->bind_param("s", $email);
$result = $stmt->execute();
if ($result->num_rows == 1) {
echo "Yes";
} else {
echo "No";
}
$stmt->close();
$conn->close();

password_verify returns false. cant find error [duplicate]

This question already has answers here:
Using PHP 5.5's password_hash and password_verify function
(4 answers)
Closed 3 years ago.
I have been trying to figure out this problem for about 2 months and can't seem to figure it out. I have a database that returns the hashed password. I can confirm this works due to printing out all the information. It can return the non-hashed and hashed password perfectly fine but when it checks the password it will always return false.
I am not sure what to do. It could be something really easy but I seem to not be able to find it.
<?php
session_start();
$dbip = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "projectNitro";
$conn = new mysqli($dbip, $dbuser, $dbpass, $dbname);
if($conn->connect_error) {
echo("Connection failed: " . $conn->connect_error);
}
$password = mysqli_real_escape_string($conn, $_GET["pass"]);
$email = mysqli_real_escape_string($conn, $_GET["email"]);
$sql = "SELECT * FROM users WHERE email='{$email}' LIMIT 1";
$query = mysqli_query($conn, $sql);
$pass = $_GET["pass"];
if($query == TRUE) {
$row = mysqli_fetch_array($query);
$db_password = $row['password'];
$db_usertype = $row['accountType'];
$username = $row['username'];
echo $password;
echo "<br>";
echo $db_password;
echo "<br>";
$verify = password_verify($pass, $db_password);
if($verify) {
$_SESSION['username'] = $username;
$_SESSION['at'] = $db_usertype;
header("Location: http://website.com");
} else {
echo("DB Email: "
.$row["email"]
."<br>Username: "
.$row["username"]
."<br>DB Password: "
.$row["password"]
."<br>AccountType: "
.$row["accountType"]
."<br>Inserted Email: "
.$_GET["email"]
."<br>Inserted Password: "
.$_GET["pass"]."<br>");
if(password_verify($_GET["pass"], $row["password"])) {
echo("epic<br>");
} else {
echo("not epic<br>");
}
}
} else {
header("Location: http://website.com");
}
$conn->close();
?>
You need to do baby steps. keep stepping up as long as it works.
Here is a simpler version of your code that should work with the password sample from the official doc: http://php.net/manual/en/function.password-verify.php
Also use die(); to debug your code in every {} block.
In your current code you redirect to a website in both cases it's really hard to track what is wrong if you are redirected!
You have useless and unclear variables, for instance $dbpass, $db_password is very ambiguous, even if you and I understand it makes it not maintainable. As well as your coding style, you need to indent!
The next step you need to check if this code works, is replace the hard coded password with a hard coded password you have with hard coded hash as well.
<?php
session_start();
$dbip = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "projectNitro";
$conn = new mysqli($dbip, $dbuser, $dbpass, $dbname);
if ($conn->connect_error){
echo("Connection failed: " . $conn->connect_error) . '<br><br>';
}
$password = 'rasmuslerdorf';//mysqli_real_escape_string($conn, $_GET["pass"]);
// $email = mysqli_real_escape_string($conn, $_GET["email"]);
// $sql = "SELECT * FROM users WHERE email='{$email}' LIMIT 1";
// $query = mysqli_query($conn, $sql);
// $pass = $_GET["pass"];
// if ($query == TRUE) {
// $row = mysqli_fetch_array($query);
$db_password = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
// $username = $row['username'];
echo $password;
echo "<br>";
echo $db_password;
echo "<br>";
if (password_verify($password, $db_password)) {
die('ok');
} else {
die('not ok');
}
// } else {
// header("Location: http://website.com");
// }
$conn->close();
?>
Here I modified slightly and added a few comments along the code to help you understand the approach.
<?php
session_start();
// This array is used only like a simple namespace.
$dbCredentials = [
'host' => "localhost",
'user' => "root",
'password' => "",
'dbname' => "projectNitro"
];
$dbConn = new mysqli($dbCredentials['host'], $dbCredentials['user'], $dbCredentials['password'], $dbCredentials['dbname']);
if ($dbConn->connect_error) {
// Should not continue script if can't connect to DB.
die("Connection failed: " . $dbConn->dbConnect_error);
}
// You should check the existence of $_GET["pass"] before using it, with empty() or isset().
$passwordToCheck = mysqli_real_escape_string($dbConn, $_GET["pass"]);// Renamed var more meaningful.
$userEmail = mysqli_real_escape_string($dbConn, $_GET["email"]);
$sql = "SELECT * FROM users WHERE email='{$userEmail}' LIMIT 1";// Don't select * if you don't need everything.
$query = mysqli_query($dbConn, $sql);
$pass = $_GET["pass"];// you already have $passwordToCheck.
if ($query) {// Don't need == TRUE
// $row = mysqli_fetch_array($query);
$db_password = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
$username = $row['username'];
echo "$passwordToCheck<br>$db_password<br>";// This is way less verbose than repeating echo and uses less echo functions.
if (password_verify($passwordToCheck, $db_password)) {// Don't need to keep this condition in a variable.
die('ok');// this is just an example to test.
} else {
die('not ok');// this is just an example to test.
}
} else {
header("Location: http://website.com");// While debugging don't redirect, put die('message');
}
$dbConn->close();
?>

mysqli_num_rows return 0 always

here am trying to get username and password from the database and if their result is found then redirect to some page but mysqli_num_rows returns 0 always i dunno why `
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `login` WHERE username = '$username' AND password = '$password'";
$run = mysqli_query($con,$query);
if (mysqli_num_rows($run) == 1) {
header("location: login.php");
}}?>
`
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ornament"; // My local DB Name
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$username = "test"; // $_POST["username"] value
$password = "test"; // $_POST["password"] value
$sql = "SELECT * FROM `ornament` WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
echo "correct";
} else {
echo "wrong";
}
mysqli_close($conn);
?>
</body>
</html>
OUTPUT:
correct
I have a database name and table name are same, But for me it's working fine.
NOTE: Please check the whether you are using correct password while getting from POST.
Any how you got a solution, Have a great day
Thanks
Muthu

Trying to get property of non-object: Using SELECT

I got little problem with my code... because I try to SELECT sth from database and then INSERT some value to another table, but in normal code from w3school
and I got error
Tryingo to get property of non-object
Here is my code:
<?php
session_start();
function connectionDB(){
$host = "localhost";
$username = "root";
$password = "";
$db_name = "project";
$conn = new mysqli($host, $username, $password, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function getID(){
$id = $_GET['id'];
return $id;
}
$login =$_SESSION['login'];
$conn =connectionDB();
$idCar = getID();
echo $idCar;
$sqluser = "SELECT ID_USER FROM login_table WHERE LOGIN = $login";
if($result->num_rows > 0)
$result = $conn->query($sqluser);
{
while($row = $result->fetch_assoc())
{
$sql = "INSERT INTO cart (id_user) VALUES ('".$row['ID_USER']."')";
}
}else echo"error";
?>
THIS IS THE CODE OF SIDE WITH PRODUCT
Please see change near your IF loop
$sqluser = "SELECT ID_USER FROM login_table WHERE LOGIN = $login";
$result = $conn->query($sqluser); //check result first
if($result->num_rows > 0) //get number of rows
{
while($row = $result->fetch_assoc())
{
$sql = "INSERT INTO cart (id_user) VALUES ('".$row['ID_USER']."')";
}
}else echo"error";

Categories