Mysqli_num_row not generating the database row correctly - php

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();

Related

autocomplete return '0 results'

recently started coding, tried to use prepared statements for the first time, but it's returning '0 results' and I can't find the error.
Autocomplete was working without prepared statements, but don't know where I'm going wrong now.
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName= "vlucht";
$mysqli = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
mysqli_set_charset($mysqli, 'utf8');
$id = $_GET['q'];
$disc = "%" . strtolower($id) . "%";
$sql = "SELECT DISTINCT postgemeente FROM overzicht WHERE LOWER (postgemeente) LIKE ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $disc);
$stmt->execute();
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["postgemeente"]. "\n";
}
} else {
echo "0 results";
}
$mysqli->close();
?>
If you are using prepare->bind->execute ..... you need to remove this line
$result = $mysqli->query($sql);
See comments
<?php
// help with debugging
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName= "vlucht";
$mysqli = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
mysqli_set_charset($mysqli, 'utf8');
$id = $_GET['q'];
$disc = "%" . strtolower($id) . "%";
$sql = "SELECT DISTINCT postgemeente FROM overzicht WHERE LOWER (postgemeente) LIKE ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $disc);
$stmt->execute();
// remove you are doing it differently now
//$result = $mysqli->query($sql);
// add to get a result object from a statement object
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["postgemeente"]. "\n";
}
} else {
echo "0 results";
}
$mysqli->close();
?>

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";
}
?>

php echo result from mysql and datetime selection

MySQL database Start = "2017-03-29 01:30:00"
The problem is:
I print the $SQL and search the record in MySQL database, it can search the record. However, I need to debug and test if there is no result, it will be expected to echo "No". But, it always to echo "Yes" no matter I can get the record in MySQL or not.
How can I fixed it.
Main purpose: Get the record if there are and Echo "No" if there don't have record
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$dbName = "fyp";
$tbName = "events";
$String_start = '2017-03-29 01:28:00';
$String_end = '2017-03-29 01:32:00';
$conn = new mysqli($serverName, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$staffID = $_SESSION['userID'];
$staff_ID = '15207800';
$sql = "SELECT *
FROM `$tbName`
WHERE `start` BETWEEN ('$String_start') AND ('$String_end')";
echo $sql;
$result=mysqli_query($conn,$sql);
if($result)
{
echo "Yes";
}
else{
echo "no";
}
?>
Mysql query only return fails if there is an issue, for successful execution it returns TRUE even if there is no record. You can achieve with follwing way
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$dbName = "fyp";
$tbName = "events";
$String_start = '2017-03-29 01:28:00';
$String_end = '2017-03-29 01:32:00';
$conn = new mysqli($serverName, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$staffID = $_SESSION['userID'];
$staff_ID = '15207800';
$sql = "SELECT *
FROM `$tbName`
WHERE `start` BETWEEN ('$String_start') AND ('$String_end')";
echo $sql;
$result=mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($result);
if($num_rows > 0)
{
echo "Yes";
}
else{
echo "no";
}
?>
Use mysqli_num_rows that will return total results returned by the query. If total > 0 then results found else no results.
To fetch rows from MySQL result set, use mysqli_fetch_assoc
$result = mysqli_query($conn,$sql);
// $result contains result set and will return `TRUE` if query was successfully executed
// and will return `FALSE` only in case of error
$total = mysqli_num_rows($result);
if($total > 0)
{
echo "Yes";
// Fetch rows from mysql result set
while($row=mysqli_fetch_assoc($result))
{
print_r($row);
}
}
else
{
echo "no";
}

Insert to table always failure

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.

Having trouble pushing data from a sql query to an array for comparison

So I am trying to compare user input from a form with data from a database, first name, last name, and email. My problem has been comparing my results with the ones that the user put in. What I am trying to do is put the results from my query into an array and then compare each array item against the input of the user. Yet I can't get through my process. What am I doing wrong?
Thank you all in advance.
P.S. I am a php newbie so any suggestions would also be appreciated
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user
$firstname = $_POST['first'];
$lastname = $_POST['last'];
$email = $_POST['email'];
//query for the database to select the columns
$queryFirst = "SELECT firstname FROM users";
$queryLast = "SELECT lastname FROM users";
$queryEmail = "SELECT email FROM users";
//query results
$resultFirst = $conn -> query($queryFirst);
$resultLast = $conn -> query($queryLast);
$resultEmail = $conn -> query($queryEmail);
$firstResult = array();
$lastResult = array();
$emailResult = array();
array_push($firstResult, $resultFirst);
array_push($lastResult, $resultLast);
array_push($emailResult, $resultEmail);
$firstValid = mysqli_result::fetch_array($firstResult);
$lastValid = mysqli_result::fetch_array($lastResult);
$emailValid = mysqli_result::fetch_array($emailResult);
//comparing query results to user input
foreach($firstResult as $comp) {
if(strpos($firstname, $comp) !== false) {
$firstname = true;
} else {
return false;
}
}
foreach($lastResult as $comp) {
if(strpos($lastname, $comp) !== false) {
$lastname = true;
} else {
return false;
}
}
foreach($emailResult as $comp) {
if(strpos($email, $comp) !== false) {
$email = true;
} else {
return false;
}
}
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($firstname && $lastname && $email = true) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Okay so first thing as already told you andrewsi, you can get all the info in one query. But if you want to select only one row, you should use a WHERE clause telling what to look for.
Check this:
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user . addslashes is for security, so they won't break your query and potentially abuse it.
$firstname = addslashes($_POST['first']);
$lastname = addslashes($_POST['last']);
$email = addslashes($_POST['email']);
//query for the database to select the columns
$query = "SELECT firstname, lastname, email FROM users WHERE firstname = '$firstname' and lastname = '$lastname' and email = '$email'";
//query results
$result = $conn -> query($query);
$numRows = $result->num_rows;
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($numRows > 0) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Haven't tested it but the idea is to check for a match in the query, not afterwards. Then if there's a match, it will return at least one row (if you defined your table correctly it shouldn't be possible to have duplicates).
Then based on that you make your choice.

Categories