Can't check if user exists in database PHP - php

I have a situation where I have to check if user exists in database, I try this:
$username = htmlspecialchars($_POST['userName']);
/* Check if username is free*/
if(!isset($error_message)) {
if(!isset($_POST["userName"])) {
$error_message = " All Fields are required";
} else {
$db_handle = new mysqli("localhost", "root", "pass", "database");
$query = 'SELECT * FROM naudotojai WHERE username = "$username"';
$result = $db_handle->query($query);
if($result->num_rows == 0) {
$error_message = "Do not exist";
}
}
}
But It doesn't work. It always returns 0 rows even if I enter a valid username that exists in database.
mysqli_result Object ( [current_field] => 0 [field_count] => 7 [lengths] => [num_rows] => 0 [type] => 0 )
Then I have second script, where I check if username is free, that works just fine:
$username = htmlspecialchars($_POST['userName']);
/* Check ir username is free*/
if(!isset($error_message)) {
if(!isset($_POST["userName"])) {
$error_message = " All Fields are required";
} else {
$db_handle = new mysqli("localhost", "root", "pass", "database");
$query = 'SELECT * FROM naudotojai where username = "$username"';
$result = $db_handle->query($query);
if(!empty($result)) {
$error_message = "Exists";
}
}
}
Could you help me out with this? Can't figure it out on my own.
EDIT: When I enter the username manually it just works fine. So the problem is with the variable in the query. But I don't get It. Why It works on one query but not the other....
$query = 'SELECT * FROM naudotojai WHERE username = admin';

You are using a single quote string to build your query, so you string $username is not replaced.
Try to use
"SELECT * FROM naudotojai where username = '$username'"
But a better approach would be to use a prepared statement to avoid SQL injection.

You can use PDO with PHP.
}else{
$dbh = new PDO('mysql:host=localhost;dbname=database', "root", "pass");
$sth = $dbh->prepare("SELECT * FROM naudotojai where username = :username");
$sth->execute(":username" => $username);
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
if($result){
// do something
}
}

Related

How to expand my PHP code to add more database fields?

I found a code php for updating database, but it's just for two field that's id and item. How about if I have 7 fields, that's id_admin, name, email, address, phonenumber, username, and password, and the table name is admin. This the code that I found.
<?php
error_reporting(0);
include("db_config.php");
// array for JSON response
$response = array();
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$result = mysql_query("update myorder set item='$item' where id='$id' ") or die(mysql_error());
$row_count = mysql_affected_rows();
if($row_count>0){
$response["success"] = 1;
$response["message"] = "Updated Sucessfully.";
}
else{
$response["success"] = 0;
$response["message"] = "Failed To Update.";
}
// echoing JSON response
echo json_encode($response); } ?>
Change these lines :
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$result = mysql_query("update myorder set item='$item' where id='$id' ") or die(mysql_error());
with these :
if( isset($_POST['submit'] ) ) {
$id=htmlspecialchars($_POST['id']);
$item=htmlspecialchars($_POST['item']);
$name=htmlspecialchars($_POST['name']);
$email=htmlspecialchars($_POST['email']);
//and so on...
$result = mysql_query("update myorder set item=$item, name=$name, email= $email ... where id=$id ") or die(mysql_error());
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
<?php
error_reporting(0);
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
// array for JSON response
$response = array();
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$stmt = $conn->prepare("update myorder set item=?,name=?,id_admin=?,email=?,address=?,phonenumber=? where id=? ");
$stmt->bind_param('ssissii',$item,$name,$id_admin,$email,$address,$phonenumber,$id);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$row_count= $stmt->affected_rows;
if($row_count>0)
{
$response["success"] = 1;
$response["message"] = "Updated Sucessfully.";
}
else{
$response["success"] = 0;
$response["message"] = "Failed To Update.";
}
// echoing JSON response
echo json_encode($response);
$stmt->close();
$conn->close();
}
?>
Always use parameterized queries when user value needs to be inserted in query.
Example:
$statement = $conn->prepare("update admin set name=?, email=?, address=?, phonenumber=?, username=?, password=? WHERE id_admin=?");
$statement->bind_param('ssssssi', $name, $email, $address, $phonenumber, $username, $password, $id_admin);
$statement->execute();

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login.php [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
i'm getting the following error
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login.php
everything else work fine... except for this !
Here's my query :
<?php
$inputuser = $_POST["user"];
$inputpass = $_POST["pass"];
$user = "root";
$password = "";
$database = "share";
$connect = mysql_connect("localhost:3306",$user,$password);
#mysql_select_db($database) or ("Database not found");
$query = "SELECT * FROM 'users' WHERE 'username'= '$inputuser'";
$querypass = "SELECT * FROM 'users' WHERE 'password'= '$inputpass'";
$result = mysql_query($query);
$resultpass = mysql_query($querypass);
$row = mysql_fetch_array($result);
$rowpass = mysql_fetch_array($resultpass);
$serveruser = $row['user'];
$serverpass = $row['password'];
if ($serveruser && $serverpass) {
if (!$result) {
die ("Invalid Username/Password");
}
header('Location: Fail.php');
mysql_close();
if ($inputpass == $serverpass) {
header('Location: Home.php');
} else {
}
}
?>
Do not use mysql_* functions. They are deprecated.
You have an error in your SQL Syntax. Change your queries to this:
SELECT * FROM `users` WHERE `username`= '$inputuser';
SELECT * FROM `users` WHERE `password`= '$inputpass';
You must use backticks, ` and not ' quotes.
And please try to combine them like this:
SELECT * FROM `users` WHERE `username`= '$inputuser' AND `password`= '$inputpass';
What if there are two users with the same password? You cannot expect all the users to use different passwords right?
Other things. You are passing the user input directly to the SQL. This is very bad and leads to SQL Injection. So you need to sanitize the inputs before you can send it to the Database server:
$inputuser = mysql_real_escape_string($_POST["user"]);
$inputpass = mysql_real_escape_string($_POST["pass"]);
Again, do not use mysql_* functions.
Update the Code
Use the following code.
// single query
$query = "SELECT * FROM `users` WHERE `username`='$inputuser' AND `password`='$inputpass'";
// your original query
$query = "SELECT * FROM `users` WHERE `username`= '$inputuser'";
Final Code
<?php
$inputuser = mysql_real_escape_string($_POST["user"]);
$inputpass = mysql_real_escape_string($_POST["password"]);
$user = "root";
$password = "";
$database = "share";
$connect = mysql_connect("localhost", $user, $password);
#mysql_select_db($database) or ("Database not found");
$query = "SELECT * FROM `users` WHERE `username`= '$inputuser' AND `password`= '$inputpass'";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
header('Location: Home.php');
die();
}
else {
header('Location: Fail.php');
die ("Invalid Username/Password");
}
?>

Check in mysql if entry exists and not insert with php

I have got a problem with testing out if a string exists in my database!
This is what I've got so far:
$db = mysqli_connect("localhost", "database", "secret", "user");
if(!$db)
{
exit("Error: ".mysqli_connect_error());
}
$search = 'SELECT * FROM table WHERE ip = $client_ip';
$result = mysqli_query($db, $search);
while($row = mysqli_fetch_object($result)) {
if (isset($row->blocked)) {
echo 'You are blocked!';
} else {
echo 'You are not blocked!';
}
But this won't work for me.
$client_ip is defined correctly before.
You need to wrap $client_ip in quotes as it is a string:
$search = "SELECT * FROM table WHERE ip = '$client_ip'";
try this one :
$search = "SELECT * FROM table WHERE ip = '{$client_ip}'";

Switch from mysql_connect to PDO: mysql_num_rows() expects parameter 1 to be resource

I had code that used mysql_connect which I understand is now deprecated to I switched to the following code (I'm working locally):
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$DBusername = 'admin';
/*** mysql password ***/
$DBpassword = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
But this now means that a function of mine breaks:
$result = mysql_num_rows($query);
Because, following the script back, the connection is not working. There is something up with my PDO connection script but I do not understand what I have done wrong. The details are correct for logging into phpMyAdmin on localhost.
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
PDO is entirely independent from the mysql extension, you will have to update your function calls as well. mysql_query for example should be a combination of prepare and execute.
As a note: Please please use Prepared Statements, your example query is completely insecure.
As an example was requested:
// initialize PDO
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
// Prepare a query
$sql = "SELECT COUNT(*) AS count
FROM users
WHERE username = ?
LIMIT 1";
$statement = $dbh->prepare($sql);
// execute the query
$statement->execute(array($username));
// retrieve the first row
$row = $statement->fetch();
if ($row['count']) echo 'The user exists';
else echo 'The user does not exist';

I have a problem with mysql and php

I have a problem, this is my code:
$db = new mysqli("localhost", "root", "", "blah");
$result1 = $db->query("select * from c_register where email = '$eml' and password = '$pass'");
if($result1->fetch_array())
{
$auth->createSession();
$_SESSION['user'] = 'client';
promptUser("You have successfully logged in!!!","index.php");
}
$db = new mysqli("localhost", "root", "", "blah");
$result2 = $db->query("select * from b_register where email = '$eml' and password = '$pass'");
if($result2->fetch_array())
{
$auth->createSession();
$_SESSION['user'] = 'business';
promptUser("You have successfully logged in!!!","index.php");
}
$db = new mysqli("localhost", "root", "", "blah");
$result3 = $db->query("select * from g_register where email = '$eml' and password = '$pass'");
if($result3->fetch_array())
{
$auth->createSession();
$_SESSION['user'] = 'employee';
promptUser("You have successfully logged in!!!","index.php");
}
$db = new mysqli("localhost", "root", "", "blah");
$result4 = $db->query("select * from k_register where email = '$eml' and password = '$pass'");
if($result4->fetch_array())
{
$auth->createSession();
$_SESSION['user'] = 'super';
promptUser("You have successfully logged in!!!","index.php");
}
else
{
promptUser("Username/Password do not match. Please try again!!!","");
}
Funny enough this code works, but I no that I went about it the wrong way. I am new with php and mysql, so please help. I also tried e.gresult4->free(); for all the variable that save the data, and I got this error: Fatal error: Call to a member function free() on a non-object in...
Don't repeat yourself. You already made your mysqli object, so reuse it. For example:
$db = new mysqli("localhost", "root", "", "blah");
$result1 = $db->query("select * from c_register...");
$result2 = $db->query("select * from d_register...");
$result3 = $db->query("select * from e_register...");
This will make your code more legible, and easier to modify later.
mysqli::query() returns a result object only after a successful query.
You need to build in a check:
if(($result1 != false) and ($result1->fetch_array())) // The same for 2,3,4...
you should get the error message using
echo $db->error;
From PHP Manual:
mysqli::query returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
So you should test it:
if ($result != false) {
...
} else {
// print error or whatever
}
Btw. it is VERY DANGEROUS not to escape variables like $eml and $pass - if a user type as $pass something like:
bleh' OR 1 = 1 OR password = 'bleh, then the whole query will look like:
select * from b_register where email = 'some#email.com' and password = 'bleh' OR 1 = 1 OR password = 'bleh'
and the user will get logged without knowing the password!
Therefore you should use: mysql_real_escape_string($eml) and the same for $pass.
Or even better: use statement preparing and parameters binding - see: http://pl2.php.net/manual/en/mysqli.prepare.php

Categories