I am storing session information in an array called 'Auth'. That array contains 2 session information: id and password. My problem is when I am using the id info for quering, it is not working. I am pretty sure it is due to the fact that the id info in my table is an int, and the one from the session array isn't. So my question is to know how to convert that session id variable into an int. Here below the function in which I am using $_SESSION(['Auth']['id']). Thank you in advance for your replies. Cheers. Marc
The PHP code where I am using the session info:
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("connect.inc.php");
function isLogged(){
if(isset($_SESSION['Auth']) && isset($_SESSION['Auth']['id']) && isset($_SESSION['Auth']['pass'])){
extract($_SESSION['Auth']);
$result = mysql_query("SELECT * FROM usr_users WHERE usr_id = '$id' AND usr_pass = '$pass'");
if(mysql_num_rows($result)==1){
return true;
}
else{
return false;
}
}
}
?>
Here the PHP code where I set the session info:
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("connect.inc.php");
$identifiant = mysql_real_escape_string($_POST['identifiant']);
$pass = sha1($_POST['pass']);
$result = mysql_query("SELECT * FROM users WHERE usr_pseudo = '$identifiant' AND usr_pass = '$pass'");
if(mysql_num_rows($result)==1){
$data=mysql_fetch_assoc($result);
$_SESSION['Auth']=array(
'id'=>$data['usr_id'],
'pass'=>$pass
);
}
echo mysql_num_rows($result);
?>
extract() is a horribly ugly function, and you should wipe its existence out of your mind.
There's no need for it, since it's purely a holdover from PHP's early "lazy" days, when it tried to do everything for you, causing in part the miserable security reputation PHP has.
You can directly embed session variables wherever you want, even when it's an arbitrarily "deep" array reference like your session is:
$sql = "SELECT ... WHERE id={$_SESSION['Auth']['id']} ...";
or even
$id = $_SESSION['Auth']['id']'
$sql = "SELECT ... WHERE id=$id";
will both work the same way, and not litter your variable namespace with useless junk.
You can cast any variable into any type by using the cast methods.
$usr_id = (int)$data['usr_id']
This would return a type of integer. If the id includes anything else but integers, 0 is returned.
http://php.net/manual/en/language.types.type-juggling.php
You should not query DB each time you'd like to check if the user is logged in. And you don't need to store password in the seesion.
You have to query db only once when you login user (your second part of the code).
And it would be better if you create a simple wrapper for your auth logic. Something like this simple class with static functions:
<?php
class Auth
{
public static function login($identifiant, $password)
{
// query db then
// $_SESSION['Auth']['id'] = value from db
return self::id();
}
public static function isLogged()
{
return (bool)self::id()
}
public static function id()
{
return (isset($_SESSION['Auth']['id'])) ? $_SESSION['Auth']['id'] : false)
}
public static function logout()
{
$_SESSION['Auth'] = array();
}
}
// usage
Auth::login($_POST['identifiant'], $_POST['password']);
if (Auth::isLogged()) {
$sql = "select * from posts where user = " . Auth::id() . "";
}
Auth::logout();
If you are "pretty sure it is due to the fact that the id info in (your) table is an int, and the one from the session array isn't".
Then here's a simple way to convert your session id from array into a variable (cast it).
$id = (int)$_SESSION['id'];
Hope it helps.
you should not enclose integers in single quotes in the SQL
try this
$result = mysql_query("SELECT * FROM usr_users WHERE usr_id = $id AND usr_pass = '$pass'");
Related
I have looked on here about if statements. I have found a few things but I am having issues figuring out the proper statement formula.
I have 2 tables in the database with the following 2 fields
table 1
rct_app_id
table 2
uid
now if the uid field matches the rct_app_id field I want it to
echo "Green Light";
if they don't match
echo "No Go"
this is my formula
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql);
$rct_app_id = ['rct_app_id'];
if ($rct_app_id == 'uid') {
echo "Green Light";
} else {
echo "No Go";
}
?>
function query($query)
{
global $connection;
return mysqli_query($connection, $query);
}
Try this. but keep in mind its hard for people to figure out whats going on by bits and pieces and it makes it harder to help you.
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql);
while(($row = mysqli_fetch_assoc($result))!=false){
$rct_app_id = $row['rct_app_id'];
if ($rct_app_id == $user_id) {
echo "Green Light";
} else {
echo "No Go";
}
}
}
?>
You need to fix two lines. $result has the results from the database, so that's the source for the rct_app_id data. Then, when you do the comparison, you need to compare the two variables.
$rct_app_id = $result['rct_app_id'];
if ($rct_app_id == $user_id) {
The way you have it, you're comparing an array to a string.
When you do this:
$rct_app_id = ['rct_app_id'];
You're actually setting the variable $rct_app_id equal to an array with one element, although the syntax is incorrect. Instead, you need to get one element of the array that is returned from the database. This assumes that you have a function called query() that is working properly and returning an array.
Instead, we need to set the variable equal to one element of the array like so:
$rct_app_id = $result['rct_app_id'];
Then, when you do a comparison like this:
if ($rct_app_id == 'uid') {
you're saying if the variable $rct_app_id is equal to the string uid, which it's not. Variables always start with $ in php, strings are quoted. The variable set earlier in the script is $user_id (from SESSION), so we need to compare to that:
if ($rct_app_id == $user_id)
UPDATE: You've specified your sql lib, I've edited the answer below to work with your updated answer.
Since you didn't specify the library, I'm making the answer and the code edits with the assumption that you're using mysql. Though all queries and return functions use similar syntax, ie: mysql_fetch_assoc() = mysqli_fetch_assoc(), pg_fetch_assoc(postgres).
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql); //What type of query runs as just query()? mysql_query would go here if this was mysql. Some Libraries offer this as a function, but since you didn't specify the library, I'm going to change it to mysql_query and proceed as if you're using mysql.
//$rct_app_id = ['rct_app_id'];//This will never work.
//You need this:
while($row=mysqli_fetch_assoc($result)){
//We only expect one result
$rct_app_id=$row['rct_app_id'];
}
if ($rct_app_id == 'uid') {
echo "Green Light";
} else {
echo "No Go";
}
function query($query)
{
global $connection;
return mysqli_query($connection, $query);
}
?>
I have written a query to get customer information from my database but say I want to use it on another page. I don't want to have to copy and paste to the other page to use it.
I have looked at a function but I don't know how to get the variables out of the function.
This is my current function:
function getCustomer($customerid) {
$getcustomer = mysql_query("SELECT * FROM hire_customers WHERE id='".$customerid."'");
$fetch = mysql_fetch_assoc($getcustomer);
$cust_firstname = $fetch['firstname'];
$cust_lastname = $fetch['lastname'];
$cust_address = $fetch['address'];
$cust_town = $fetch['town'];
$cust_postcode = $fetch['postcode'];
$cust_cont1 = $fetch['contact1'];
$cust_number1 = $fetch['contactnumber1'];
$cust_cont2 = $fetch['contact2'];
$cust_number = $fetch['contactnumber2'];
$cust_email = $fetch['email'];
$cust_idform1 = $fetch['idform1'];
$cust_idnfo1 = $fetch['idinfo1'];
$cust_idform2 = $fetch['idform2'];
$cust_idinfo2 = $fetch['idinfo2'];
$cust_enterdby = $fetch['enteredby'];
}
This is my customer page
getCustomer($customerid);
echo $cust_firstname;
but nothing is echoed out.
Do I need to be looking at a class or object to do this? Have I gone wrong with my function.
What I would like to do is have a PHP file with all my customer functions (update, select, etc) in one place.
I think you should just return $fetch and then access it as a variable outside of the function.
function getCustomer($customerid) {
$customerid = mysql_real_escape_string($customerid);
$getcustomer = mysql_query("SELECT * FROM hire_customers WHERE id='".$customerid."'");
$fetch = mysql_fetch_assoc($getcustomer);
return $fetch;
}
$data=getCustomer($customerid);
echo data['firstname'];
This should get you started:
function getCustomer($customerid) {
$getcustomer = mysql_query("SELECT * FROM hire_.. etc");
$customer_data = mysql_fetch_assoc($getcustomer);
return $customer_data; // return here
}
$customer = getCustomer($customerid);
$cust_firstname = $customer['firstname'];
you need to return a value from your function return $variable;
In your code, variable $cust_firstname; is visible only inside that function.
Please read this: PHP variable scope
It works like this to reduce memory usage on web server - when function ends - variable is destroyed and memory freed.
Basically - you have to return that value somehow. Dave Chen wrote nice answer above/below, you can use his code.
BTW you can use extract(); function and reduce your code size and save a lot of time.
It works like this:
$fetch = mysql_fetch_assoc($getcustomer);
extract($fetch, EXTR_PREFIX_ALL, "cust_"); // creates variables from associative array
echo $cust_firstname; // magic! :)
I have a script that follows that is supposed to collect data from a field"UserID" in my sql table, submit all data into an array, and then compare a variable to whats in the array. If the value of the variable is already in the array, tell the user that that value is invalid.
$sql = "SELECT *" //User info
. " FROM Users" ;
$result = mysql_query($sql);
//insert where line for assessorid
$users = array();
while(($user = mysql_fetch_assoc($result))) {
$users[] = $user;
}
foreach($users as $user){
$user['UserID'];
}
I need the output of $users to be equivalent to array('user1','user2','user3');
Whats happening is data comes in from a form as $user_name. I want to use this in a statement like follows:
if(in_array($user_name,$users)){
echo "username available"
}
else{
echo "not available"}
I tried using the extract function, but that just created a big mess.
Im not sure what is incorrect about what I'm doing, unless the format of $users as an array cannot be parsed in the in_array() function as it is formatted currently. Any advice is much appreciated. Thanks!
$sql = "SELECT USERID FROM Users" ;
$result = mysql_query($sql);
$users = array();
while(($user = mysql_fetch_assoc($result))) {
$users[] = $user['USERID'];
}
When you are saying
$users[] = $user;
You are not specifying which column in the result set to be appended to the array.
Maybe I am missing something... Why not do it like this:
SELECT UserID FROM Users WHERE Username = 'username'
Then just use mysql_num_rows() to check if the username already exists or not. This should be both faster and more efficient (memory-wise).
In that case, you collect all data from the database and need to do some inefficient processing in PHP as well. It is better to query for that value to see if it is in the database, so:
$username = mysql_real_escape_string($username);
$query = "
select
count('x') as usercount
from
users u
where
u.username = '$username'";
The, if the 'usercount' is 0, the username does not exist. If > 0, the username does exist. This way, you let the database do the work it is designed to do, and the only value that is actually retreived is that single number.
Have you tried modifying your query? Currently you are getting all of the values for every user, but you just seen to need UserID. You could do this:
$sql = "SELECT UserID FROM Users";
$result = mysql_query($sql);
$users = array();
while(($user = mysql_fetch_assoc($result)))
{
$users[] = $user['UserID'];
}
// ...
if (in_array($user_name, $users))
{
echo 'Username not available';
}
else
{
echo 'Username available';
}
Or you could just look up in the database for the given username:
$sql = 'SELECT count(*) FROM Users WHERE UserID = '.mysql_escape_string($user_name);
$result = mysql_query($sql);
// and then just check if the resulting row is equal to 0
Are you attempting to write a script that will check if a username is taken?
If so, it may be easier (and more efficient) to structure the actual query towards this end rather than relying on the programmatic approach.
$sql = "SELECT COUNT(*) FROM Users WHERE Username = '$username'";
Then you could apply this result to a count and allow the user to register or not based on whether a value greater than zero (a user has already taken that name) or not (its free) is returned.
As has been mentioned, that is a rather inefficient way to check for an existing username. The suggestions for modifying your query are good advice.
However, to address the problem with the code you provided:
in_array() will not detect the presence of a value in a multi-dimensional array. Your $users array probably looks something like this:
$users = array(
array('userID', 'foo', 'bar'),
array('userID', 'foo', 'bar'),
array('userID', 'foo', 'bar')
)
and in_array will not search below the first set of indexes. If this is really what you want to do, see this question: in_array() and multidimensional array
Can you do that? I just tried but it doesnt seem to work.
I have dbc.php included at top of my page, and in dbc.php at the bottom i created this function:
function getUserInfo($id) {
$thaString = mysql_query("SELECT * FROM users WHERE id = '$id'");
$thaString2 = mysql_query("SELECT * FROM users_profile WHERE uID = '$id'");
$showUR = mysql_fetch_array($thaString);
$showURP = mysql_fetch_array($thaString2);
}
So it would be easier for me to call them instead of running the queries all the time when i need them in other pages..
But when i try to do:
getUserInfo($showInfo["bID"]);
echo $showUR["full_name"];
I dont get any result, is there a smarter way to do this, if so how?
It's an issue of scope: $showUR is set inside getUserInfo(), so it's not available to the echo outside the function. There are lots of potential modifications you could make, but you may want to assign your values into an array and then return that array:
function getUserInfo($id) {
$user = array();
$thaString = mysql_query("SELECT * FROM users WHERE id = '$id'");
$thaString2 = mysql_query("SELECT * FROM users_profile WHERE uID = '$id'");
$user['showUR'] = mysql_fetch_array($thaString);
$user['showURP'] = mysql_fetch_array($thaString2);
return $user;
}
$user = getUserInfo($showInfo["bID"]);
echo $user['showUR']["full_name"];
Your functions have to return something for the values to be used, or $showUR and $showURP will just get lost once the function exits (ie: the scope will change). Something like:
function someFunc($arg) {
return "Hello, I am {$arg}";
}
$showUR = someFunc('name');
echo $showUR;
And please don't call stuff $thaString. First because it's a misnomer (mysql_query() doesn't return a string, it returns a resource or a boolean), Second because "tha" is so lame.
Let your function return the variable.
And then use $showUR = getUserInfo(...)
If you declare them outside the function, and then as globals inside the function you should be able to use them as you are now.
I'm trying to stuff a variable into a SQL query to return a value to a page.
$sql = 'SELECT account FROM users WHERE uid = arg(1)';
Where arg(1) = the user currently being viewed. I am outputting arg(1) at the top of the page, so I know it's there, but Drupal doesn't seem to want to take it. I've tried escaping several different ways. Below is the full code
function accountselect_getclientaccount() {
global $user;
$sql = 'SELECT account FROM users WHERE uid = arg(1)';
$result = db_result(db_query($sql));
return $result;
}
You could try:
$uid = arg(1);
$result = db_result(db_query("SELECT account FROM {users} WHERE uid = %d", $uid));
To avoid sql-injection, you should use placeholders (see db_query for more info):
$result = db_query("SELECT * FROM {users} WHERE uid = %d", arg(1));
Also note that db_result is meant for single-column, single-result queries. You probably want to use db_fetch_object. Additionally, there isn't a column in the users table called account.
function accountselect_getclientaccount() {
return (arg(0) == 'user') ? db_result(db_query('SELECT account FROM {users} WHERE uid = %d', arg(1))) : FALSE;
}
I don't know why you're using the global $user. Maybe you should be using $user->uid instead of arg(1)? This would save you checking arg(1) is actually a user ID.
This might be better:
function accountselect_getclientaccount($account) {
return db_result(db_query('SELECT account FROM {users} WHERE uid = %d', $account->uid));
}
Also: see the user hook. It might be best practice to return the 'account' col on the load operation (if you're not doing that already)
http://api.drupal.org/api/function/hook_user/6