Retrieving a single fetch value from a function using PHP - php

//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

Related

Assign value to variable inside Function

I have a function as stated below. But, I'm not sure on how to assign the values roles from database in the variable. Because I need the values roles' to decide either the user is admin or not. Velow is my code.
function find_user_by_username(string $username){
//find users in the database acourding to Input
$sql = 'SELECT username, password, roles from users WHERE username=:username';
$statement = dbConnect()->prepare($sql);
$statement->bindValue(':username', $username, PDO::PARAM_STR);
$statement->execute();
return $statement->fetch(PDO::FETCH_ASSOC);
}
Kindly advise. Thanks.
The best method is to save the required information in the session when logging in.
Or use the following code:
$result = find_user_by_username($username) ;
if ($result["roles"] == 'admin'){}

Function/Trigger already in use?

Im having problems getting an update function to work. The function marks badges as seen so that they are hidden from a notification window.
The function is called when the user clicks a button to mark them as seen.
I have two triggers on the table its trying to update which I think may be causing the problem.
The problem is : Can't update table 'users' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Triggers:
Function:
function markAsSeen() {
require "connect.php";
$seen = mysqli_query($connection,"Update userbadges
INNER JOIN users ON users.id = userbadges.user_id
SET seen='1'
WHERE studentid = '".$_SESSION["studentid"]."' && seen=0") or die(mysqli_error($connection));
while ($data = mysqli_fetch_array($seen)) {
echo 'Done';
}
}
Is there any way around this?
Your issue is that the update_users_trigger trigger makes changes to the contents of the table users, while the query that is triggering the execution of this trigger also uses the table users.
You will need to adjust your query so that this deadlock doesn't occur. It isn't clear which fields are from each table, but I suspect that in your initial query you need to join on users so that you can query on studentid.
You could create a different function to get the userID that you need something like the following:
require_once "connect.php";
function getUserIDFromStudentID($student_id, mysqli $connection)
{
$query = 'SELECT id FROM users WHERE studentid = ? LIMIT 1';
$stmt = $connection->prepare($query);
// Replace the below s to an i if it's supposed to be an integer
$stmt->bind_param("s", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$record = $result->fetch_object();
$result->free();
if ($record) {
return $record->id;
}
}
function markAsSeen(mysqli $connection) {
$user_id = getUserIDFromStudentID($_SESSION["studentid"], $connection);
if (! $user_id) {
throw new Exception('Unable to get user id');
}
$seen_query = 'UPDATE userbadges SET seen = 1 WHERE user_id = ? and seen = 0';
$stmt = $connection->prepare($seen_query);
// Replace the below s to an i if it's supposed to be an integer
$stmt->bind_param("s", $user_id);
$result = $stmt->execute();
if (! $result) {
die(mysqli_error($connection));
}
echo 'Done';
}
Passing the connection object around rather than requiring a global file to be required every time will allow for more flexibility.

How to get user_id with this code

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....

Obtaining an specific db value

I'm using PDO for a connection into my db. There, I have a table where I store the users. In that table I have 5 columns: id, username, password, mail and sex.
What I really want is to store in a SESSION variable, the sex of the user that has been logged in. I don't know exactly what to use, because all the examples that I've seen, are usually for printing all the results of the db into the webpage with a foreach statement, but that isn't what I want.
Actually, this is the code that I have:
$connection = new PDO('mysql:host=localhost;dbname=db', "user", "password");
$sql = 'SELECT * FROM users WHERE username = :username AND password = :password';
$statement = $connection->prepare($sql);
$statement->bindParam(':username', $_POST['username'], PDO::PARAM_STR, 12);
$statement->bindParam(':password', $_POST['password'], PDO::PARAM_STR, 30);
$result = $statement->execute();
if ($result) {
$result = $statement->fetchAll();
if (!empty($result)){
$_SESSION['login'] = true;
$_SESSION['username'] = $_POST['username'];
echo 'Hello '.$_POST['username'].', you have been connected successfully.';
}
else {
echo 'Sorry, this user do not exist.';
}
}
So, this is correctly working.
But now, what I want is to store the sex value from the db in a $_SESSION['sex'] variable. How can I do that?
Thanks.
You can just add in the session after username, you have already slected from your query
$_SESSION['username'] = $_POST['username'];
$_SESSION['sex'] = $result[0]['sex'];
You might want to remove $result from query execution, so this line
$result = $statement->execute();
Will be
$statement->execute();
Just assign it from the result row:
$_SESSION['sex'] = $result[0]['sex'];
You have to use [0] because you used fetchAll, which returns a 2-dimensional array of rows and columns.

Receive multiple columns from one sql request in PHP

I am working on a friend list function and I can't figure out how to correctly receive the values.
My code looks like this:
$getuid = $mysqli->prepare("SELECT `uid` FROM `users` WHERE name = ? OR name = ?");
$getuid->bind_param("ss", $user, $friend);
$getuid->execute();
$getuid->bind_result($uid);
$getuid->fetch();
$getuid->close();
$resetpass = $mysqli->prepare("INSERT INTO `friendlist` SET `friend1`=?, `friend2`=?, `accept`=0");
$resetpass->bind_param("ss", $uid[0], $uid[1]);
With the first query I get exactly two uid values back. I want to use them in the second query. It seems like bind_result is not working, neither as array nor when using two values in bind_result. How can I do this using mysqli. I can't use get_result because I'm on PHP 5.2 .
Anyone able to help me?
I think you need something like this. I have not tested it and there are probably even better ways to do this. I just tried the quickest change i could make to your original code to get it to work.
$query = "SELECT uid FROM users WHERE name = '".$user."' OR name = '".$friend."'";
$getuid = $mysqli->query($query);
if($uid = $getuid->fetch_assoc())
{
$query = "INSERT INTO friendlist SET friend1= '".$uid['uid'][0]."', friend2='".$uid['uid'][1]."', accept=0";
$mysqli->query($query)
}
$getuid->close();
Okay I finally understood the concept of fetch.
In order to receive all the values I have to retrieve them in a while-loop.
Here is the solution:
$getuid = $mysqli->prepare("SELECT `uid` FROM `users` WHERE name = ? OR name = ?");
$getuid->bind_param("ss", $user, $friend);
$arra = array();
$getuid->execute();
$getuid->bind_result($uid);
while ($getuid->fetch()) {
$arra[] = $uid;
}
Now I can call the array values using $arra[0] and $arra[1]

Categories