Php PDO connection to database - php

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']." ";

Related

one query, one table, two count()

I want to check if username and email taken in my registration script.
This is how I check with query:
$emailcheck = "SELECT COUNT(email) AS nume FROM members WHERE email = :email";
//bindValue
//execute
//fetch
if($rowe['nume'] > 0){
$errors[] = "E-mail exist.";
}
And also I'm doing the same thing for username;
$usercheck = "SELECT COUNT(username) AS numu FROM members WHERE username = :username";
//bindValue
//execute
//fetch
if($rowu['numu'] > 0){
$errors[] = "Username taken.";
}
*
I want to go one step further and handle all of stuff with one query.
But I couldn't came up with such query.
I tried:
$check = "SELECT COUNT(username) AS numu and COUNT(email) AS nume FROM members WHERE username = :username OR email = :email";
but probably It's ridiculous.
How to handle what I want with one query?
And after I want to check like that:
if($row['numu'] > 0){
$errors[] = "Username taken.";
}
if($rowe['nume'] > 0){
$errors[] = "E-mail exist.";
}
So it will be less code, instead of connecting same table twice and bindValue, execute, fetch for second time.
You can just do Union All to unite those queries:
SELECT COUNT(email) AS num FROM members WHERE email = :email
UNION ALL
SELECT COUNT(username) AS num FROM members WHERE username = :username
Then extract 2 according rows.
OR, MySQL allows this thing:
SELECT
(SELECT COUNT(email) FROM members WHERE email = :email) as nume,
(SELECT COUNT(username) FROM members WHERE username = :username) as numu
if you want 1 rows with 2 columns.
Do that only if you need to see which one is already present. Otherwise just do this:
SELECT 1 FROM members WHERE email = :email OR username = :username LIMIT 1
Yes, consider not doing count() because you don't need to count all the rows. You just need to stop if you find just one. So either do a LIMIT or IF EXISTS()
I don't think you really need to count. Assuming you want to check if either username or email already exist because they are required to be unique on your user table, you can do this:
First, add a unique index to each of those columns in your database. You may already have this, but if you want those values to be unique, this will ensure that even if your PHP code fails to do so for some reason.
Then you can use this query:
SELECT username, email FROM members WHERE username = :username OR email = :email
This will return either zero, one, or two rows, where:
0 = neither username nor email was found
1 = one row was found having either username, email, or both
2 = username was found in one row and email was found in another
Then you can loop over your results, comparing them to the user input, and set your errors.
while ($row = //fetch) {
if ($row['username'] == $username) {
$errors[] = "Username taken.";
}
if ($row['email'] == $email) {
$errors[] = "E-mail exist.";
}
}
You can try this after removing and between count
$check = "SELECT COUNT(username) AS uname ,
COUNT(email) AS uemail FROM members
WHERE (username = :username OR email = :email)";

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
}

How do I find out a specific row ID from a table?

Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);

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.

authentication query in two table?

my website has separate tables for users and admin
now i want to give the privilege to access admin area to some users
my problem is with admin and users table
i dont know if i should copy authentication data from user table to the admin table so they can login in to the admin are , or perform a query to search both tables for username and password and just use level column to verify their access?
something like this ?
$sql = "select `password` , `level` from `admin` where `username` = '$username' UNION
(SELECT `password` , `level` FROM `users` where `username` = '$username') LIMIT 1 ";
$result = $db->query($sql);
while($row = mysql_fetch_assoc($result)){
if($password == $row['passwor'] && $row['level'] != 0)
echo 'welcom to admin area';
else
echo 'login faild';
}
I see you are storing passwords in the clear in your database.
This is a major security risk and should never be done.
Passwords should always be stored as salted hashes using a secure hash function.
I also fail to see the use for separate tables for admins and non-admins.
I recommend you alter your table layout.
table user
-------------
id unsigned integer auto_increment primary key,
username varchar(100) not null,
salt varchar(20) not null,
passhash varchar(48) not null,
isadmin boolean not null default false
Query your table with:
SELECT u.id, u.isadmin FROM user u
WHERE u.username = '$username'
AND passhash = SHA2(CONCAT(u.salt, '$password'),512)
AND isadmin = 1
When creating a user use:
INSERT INTO user (username, salt, passhash, isadmin)
VALUES ('$username', '$salt', SHA2(CONCAT('$salt','$password'),512), '$isadmin')
You may use LEFT JOIN and no need for a loop :
$sql = 'SELECT `a`.`password`, `a`.`level` FROM `admin` AS `a` LEFT JOIN `users` ON `a`.`username` = `u`.`username` WHERE `a`.`username` = "'.$username.'" LIMIT 1';
$result = $db->query($sql);
$row = mysql_fetch_assoc($result);
if($password == $row['passwor'] && $row['level'] != 0)
echo 'welcom to admin area';
else
echo 'login faild';
But you should create a field in your users table and use an int to give rights like :
0 is a user, 1 is a super user, 2 moderator and 3 admin... this is an example. Then you use DEFINE in PHP to setup your class. Also, encode your password. I recommend SHA-512.

Categories