Find username within specific column - php

I am trying to get this PHP working where it returns true or false if the username exists in the username column on the database:
$data = array($_POST["username"]);
$db = new PDO('mysql:host=localhost;dbname=Example;charset=utf8', 'Example', 'Example');
$stmt = $db->prepare("SELECT FROM Members (username) WHERE username=?");
$stmt->execute($data);
if(mysql_num_rows($stmt)>=1)
{
echo"true";
}
else
{
echo "false";
}

SELECT FROM
Does not select anything.
You need to specify what you need to select or just * to select all
SELECT `username` FROM
OR
SELECT * FROM

SELECT * FROM Members WHERE username=?

Try this statement
SELECT * FROM Members WHERE username
or
SELECT username FROM Members WHERE username

You can fetch a boolean result, from the sql query itself, with minor modification.
SELECT
count(username) > 0 as user_exists
FROM Members
WHERE username=?
In PHP script just read the result that has either a true (1) or false (0) as value.

Related

Count num of rows in PDO prepared statements

I have two questions regarding codes below.
I know the second code is correct but not sure if first is also correct both do same thing first one is just easy to write.
I want to count the number of rows in database for the selected element if ($query->num_rows == 1) { doesn't work so how to rowcount for the code below.
First code:
$query = $db->prepare("SELECT * from users WHERE username = :username");
$query->execute(array(':username'=>$un));
Second:
$result = "SELECT * from users WHERE username = :username";
$query = $db->prepare( $result );
$stmt->bindValue(':username'=>$un);
$query->execute($stmt);
You don't need the row count. You need just the row itself. So, just fetch it, from the first variant, which is ok.
As of the row count, you are supposed to be able to get the proper function name from manual.
$query = $db->prepare("SELECT 1 from users WHERE username = ?");
$query->execute(array($un));
if ($query->fetch())
{
// found
}
First, if you want to ensure that only one username is selected, you can use LIMIT in your MySQL statement
SELECT * from users WHERE username = :username ORDER BY id DESC LIMIT 1
Or:
SELECT DISTINCT(username) from users WHERE username = :username```
Even better, when creating the table, you can require that the username is unique:
CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
...
PRIMARY KEY (id),
);
Second, to verify that a row was actually retrieved from the dabase, you can use fetch:
$query = $db->prepare("SELECT * from users WHERE username = :username");
$query->execute(array(':username'=>$un));
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) {
// Row exists
}

Php PDO connection to database

I have database with 2 table. Students and Profesors. I create one more login table and there are all email and passwords from students and profesors. I want to create that Student try to login that will send him on some student.php and when profesor try to login it will send him on profesor.php
I try with this code, but it always return me 1. So this is not good options..
if(isset($_POST['Submit'])){
$sql= "SELECT COUNT (*) FROM `students` AND 'Profesors' WHERE `username` = :username and `password` = :password ";
$result = $connection->prepare($sql);
$result->bindParam(":username" ,$_POST['username']);
$result->bindParam(":password" ,$_POST['password']);
$result->execute();
$num=$result->rowCount();
if($num > 0){
header("location:index.php");
}else{
header("location:login.php");
}
I need some idea, how to change my datebase or this login code.
I would personally not let professors and student use the same login. Now to answer the question I would change my query to the following:
SELECT user_type FROM `login_table`
WHERE `username` = :username AND `password` = :password
once query return result I would check the user_type field and redirect accordingly.
$num=$result->rowCount();
if($num > 0){
$data=$result->fetch();
if($data['professor']){
header("location: professor.php");
}else{
header("location: student.php");
}
}else{
header("location:login.php");
}
Here's an idea of how you might want to structure this
Have a table defining types of accounts, maybe
account_type_id | account_type_desc | account_type_dest
Where the first is unique key, the second is "Professor" "Student" or anything else you add, and the third is where you want to send that type of user. "student.php", "professor.php", etc
Then your user table would be something like
account_id | account_type_id | email | password
Then you can query the user table for a user matching the person trying to login in, authenticate their password, grab the account type id and turn it against the table of account types and then you can act based on that information
You can do this using a subquery and union statements. You can create a single table out of the two using a union statement
$subquery = "SELECT username,password FROM `students` UNION SELECT username,password FROM `Profesors`";
Then run a query using the subquery as your source table
$sql= "SELECT * FROM (" . $subquery . ") WHERE `username` = :username and `password` = :password ";
Then use rowCount to determine how many rows were returned.
You want to use php session or issue a cookie to the user for a proper and secure user login.
In your query I think you wanted:
$sql= "SELECT COUNT (*) FROM `students` AND 'Profesors' WHERE `username` = ".$_POST['username']." and `password` = ".$_POST['password']." ";

Checking whether username exists or not code in sql and php

I have written a code to check whether the username exists in the database or not. It seems to return that there is no such username exists even if there's a same username existing.
$conu=mysqli_connect("localhost","db_user","db_pass","db_name");
$result = mysql_query("SELECT 1 FROM member WHERE username = $username");
if ($result && mysql_num_rows($result) > 0) {
$user_err = "<i><span class='error'>Usernme already exists</span></i>";
$errflag = true;
}
elseif(preg_match("/^[0-9a-zA-Z_]{5,}$/", $username) === 0) {
$user_err = "<i><span class='error'>Usernme must be bigger than 5 chararacters and can contain only digits, letters and underscore</span></i>";
$errflag = true;
}
Try
mysql_query("SELECT username FROM member WHERE username = '$username' LIMIT 1;");
SELECT 1 is not actually using the database; it's always returning 1, hence why your result is always the same regardless of the contents of the member table.
Usernames I take it are some sort of varchar? If that is the case, you might want to put its value in quotes:
$result = mysql_query("SELECT `username` FROM `member` WHERE `username` = '".$username."' LIMIT 1;");
your query is subject to sql injections btw.
At first, you are trying to return a column that probably doesn't exist: "1"
Second, I hope that you are cleaning the $username or else you are allowing anyone to inject your database.
The correct query is
mysql_query("SELECT * FROM `member` WHERE `username`='$username'");
You are using mysqli to connect, but mysql to perform your query.
When you SELECT 1 FROM member WHERE username = $username, the result will always be 1.
You need to put $username in the query in quotes. Something like SELECT username FROM member WHERE username = '$username'.
You forgot to include the part of the code for when there is no such username in your posting.

return true if value is in mysql

I am writing a program that should connect to a php file on my website. In the C# they enter a value (password). The password would then be sent to the webpage (example.com/example.php?param=<password>)
I know how to make the program send the password but I don't know how to compare the value entered to a value in a table of my mysql database. If the value is in the database I want it to return true.
sql
SELECT `password`
FROM `tableName`
WHERE `password` = :password
:password should be the value you are checking for in the database
select 1 from your_table where password = 'thepass'
$result = mysql_query("SELECT * FROM table1 where password = '$password'", $link);
$num_rows = mysql_num_rows($result);
if($num_rows >0)
return true;
return false;

PHP mysql_num_rows() Returns error

I have a PHP login script. This is the part where the person can create a new user. My issue is I want to check if the user exists, and if the username does not exist the the table, than create the new user. However, if the user does exist, I want it to return an error in a session variable. Here is the code I have right now. This doesn't include my DB connections, but I know they do work. Its num_rows() that is being written as an error in the error_log file. Here is the code:
$username = mysql_real_escape_string($username);
$query = "SELECT * FROM users WHERE username = '$username';";
$result = mysql_query($query,$conn);
if(mysql_num_rows($result)>0) //user exists
{
header('Location: index.php');
$_SESSION['reg_error']='User already exists';
die();
}
else
{
$query = "INSERT INTO users ( username, password, salt )
VALUES ( '$username' , '$hash' , '$salt' );";
mysql_query($query);
mysql_close();
header('Location: index.php');
The error it is giving me is
mysql_num_rows(): supplied argument is not a valid MySQL result resource in [dirctory name]
mysql_num_rows()
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
Instead of doing SELECT * and then mysql_num_rows(), you can do a SELECT COUNT(*) and then retrieve the number of rows, by fetching the field (that should be 0 or 1). SELECT COUNT will always return a result (provided that the query syntax is correct of course).
Also, change the query:
$query = "SELECT * FROM users WHERE username = '$username';";
into
$query = "SELECT * FROM users WHERE username = '"
. mysql_real_escape_string($username) . "';";
Just out of curiosity, have you ever heard of upserts? I.E., "insert on duplicate key". They'd be useful to you in this situation, at least if your username column is a unique key.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$username = mysql_real_escape_string($username);
i think you have to replace the above to
$username = mysql_real_escape_string($_POST[$username]);

Categories