I have this code here:
$selectUserQuery = 'SELECT user_id, email_address, password FROM user WHERE email_address = :email_address AND password = :password AND confirm_status = 1';
$prepSelectUser = $conn->prepare($selectUserQuery);
$prepSelectUser->bindParam(':email_address', $emailEnc, PDO::PARAM_STR);
$prepSelectUser->bindParam(':password', $passwordEnc, PDO::PARAM_STR);
$prepSelectUser->execute();
$userResult = $prepSelectUser->fetchAll();
$userCount = count($userResult);
I select the email address and password to see if they match (this is for login) and I need the user_id to start a session with the user_id as its value. However, the fetchAll() function returns an array of the results, but I need the user_id separately, only to use it as a value for the session.
How do I fetch the user_id separately?
Try this:
foreach ( $userResult AS $row ) {
var_dump($row[0]);
}
It should be in Userresult::
normaly is hould be:
$userResult[0]['user_id'] (1st user)
$userResult[1]['user_id'] 2th user
$userResult[5]['user_id'] 6th user....
Related
First off, I know about sql injection and that my code is not foolproof, prone to injection etc. Will be working on that next.
Now : from my Android app to my PHP file I submit a JSON array of phone numbers like :
[{"phone_number":"+12345678"},
{"phone_number":"+23456789"},
{"phone_number":"34567890"},
{"phone_number":"45678901"}
etc... etc...
These are contacts in my app user's phone. If these contacts are people who are also users of my app then I want to insert those numbers into my contacts table.
But I can't get it to work. mysqli_fetch_assoc isn't working correctly. I don't know why.
In my contacts table I have 3 columns - an auto increment, user_id and contact_id. The first two values are inserted correctly but the contact_id is always put in as '0', which is wrong.
Here is my code :
require('dbConnect.php');
//this is me, +567890123, my user_id in the user table
$user_id = '20';
//post all contacts in my phone as a JSON array
$json = $_POST['phonenumber'];
$array = json_decode($json);
foreach ($array as $value) {
$phonenumber = $value->phone_number;
$sql = "SELECT username FROM user WHERE username = '$phonenumber'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
echo "phonenumber is " . $phonenumber . "<br>";
// we want to put $phonenumber in the contacts table, as one of +567890123 contacts
// In the user table get the associated rows of $phonenumber
while ($row = mysqli_fetch_assoc($result)) {
// get the associated user_id in that row, that's what we want to put into the contacts table
$contact_id = $row['user_id'];
$insert_into_contacts_command = "INSERT INTO contacts VALUES(NULL, '$user_id','$contact_id')";
$insert_into_contacts_table = mysqli_query($con, $insert_into_contacts_command);
}
} //if +353864677745 is NOT in the user table...
else {
echo 'not a match.';
}
}
$contact_id = $row['user_id'];
Here $contact_id will be null, because you are trying to access not existing field $row['user_id'] of the $row .
Actually there is only one field username in your results set, as you specified:
$sql = "SELECT username FROM user WHERE username = '$phonenumber'";
Try to change your query to this:
$sql = "SELECT user_id, username FROM user WHERE username = '$phonenumber'";
Your query selects the column username, not userid.
You haven't posted anything about the table user, so it's hard to suggest a new query, but I guess it's the following:
$stmt = mysqli_prepare($con, "SELECT userid FROM user WHERE username = ?");
$stmt->bind_param("s", $phonenumber);
$stmt->execute();
$stmt->bind_result($userid);
while ($stmt->fetch()) {
// Work with $userid
}
You'll note that this uses a prepared statement with a bound parameter. That way, your code is not prone to SQL injections.
Im creating a webpage for a game server that only had a registration page. All the users has registred and for some dum reason, it saved the password as username:password, so if the username is Meko and password is 1234, the actually password is "Meko:1234" Im now trying to make a login but im not sure how I should check that password. I have this sql query and tried to add $user_username: in front, but it didnt seem to work:
$query = "SELECT * FROM account
WHERE username = '$user_username'
AND sha_pass_hash = '$user_password'";
It needs to be $user_username:$user_password
I hope you can help me :)
If what you have stored in the database is an SHA1 checksum, then that's what you will need to compare.
The details are pretty sketchy.
Assuming that the row was saved into the database as
INSERT INTO `account` (`username`, `sha_pass_hash`, ...
VALUES ('Meko', SHA1('Meko:1234'), ...
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
if those are the values you want to pass into the database query, then
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = SHA1( CONCAT( ? ,':', ? )';
$sth = $dbh->prepare($sql);
$sth->bindValue(1,$user_username, PDO::PARAM_STR);
$sth->bindValue(2,$user_username, PDO::PARAM_STR);
$sth->bindValue(3,$user_password, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
// matching row found
} else {
// no matching row found
}
$sth->closeCursor();
If you didn't use the MySQL SHA1 function and used some other function to calculcate the hash, then use that same function when you do the check.
That is, if the row was inserted by a statement of a form more like
INSERT INTO account (username, sha_pass_hash, ... )
VALUES ('Meko','7c4d046a92c441c426ce86f15fa9ecd1fc1fd5f1', ... )
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
Then your query to check for the existence of the row would be something like this:
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = ?';
calculate the password hash, the same way as when it was originally done
$user_sha_hash = sha1( $user_username . ':' . $user_password) ;
And prepare and execute the query, passing in the SHA checksum string
$sth = $dbh->prepare($sql);
$sth->bindValue(1, $user_username, PDO::PARAM_STR);
$sth->bindValue(2, $user_sha_hash, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
//
} else {
//
)
$sth->closeCursor();
I think you on php ?
$username = 'Meko';
$user_password = '1234';
$altered_pass = $user_username.':'.$user_password;
if($stmt = mysqli_prepare($con,"select * from account where username = ? and sha_pass_hash = ?") ){
mysqli_stmt_bind_param($stmt,'ss',$user_username,sha1($altered_pass));
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt)){
//"yup";
}
else{
//"nope";
}
mysqli_stmt_close($stmt);
}
mysqli_close($con);
You do not specify explicitly but assuming that your sha_pass_hash contains a hashed value of the following format: hash(username:password) then hash '$user_username' + ":" + '$user_password' first and then compare it to your password.
$search = $username.":".$password;
$query = "SELECT * FROM account WHERE password = ".$search;
IMPORTANT:
I very much hope you are preparing your statements and binding your parameters to prevent SQL injection attacks. If you are not, let me know and I can help you out in more detail so that your database is secure.
Also, I recommend that you create another table and fill it in with the values inside this account table. The previous answer is a quick fix so that your users can login meanwhile, but by no means should the previous table stay as it is.
Let me know if you need any more help :)
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)";
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
}
//This is my function in retrieving the id of the user base from its email and pass. this is for functions.php
function getID($email,$pass)
{
$pdo = new PDO(connection here);
$stmt = $pdo->prepare('SELECT id user where email = :email and pass = :pass LIMIT 1');
$stmt->execute(array(':email'=>$email, ':pass'=>md5($pass)));
$result = $stmt->fetch();
return $result['id'];//Is this the right way of returning a value from a fetch value?
}
//this is for user.php.
include 'function.php';
session_start();
$_SESSION['id'] = getID($_POST['email'],$_POST['pass']);
Is this the right way of retrieving it? but i do not get any values from it. Need help thanks!
Your query is missing a FROM.
SELECT id FROM user WHERE email = :email AND pass = :pass LIMIT 1