passing integer to function.

I have a function to get all events information where users are invited.
in order to do so, I would like to pass user_id(INT) by reference.

function getAllEvents($read, $user_id) {
$sql = ‘SELECT * from events as e, invitations as i where e.event_id=i.event_id AND i.user_id= $user_id’;
return $read->fetchAll($sql);
}

it seems the way i used ‘$user_id’ is wrong, therefore, i keep getting the following message.

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘$user_id’ in ‘where clause’

All I want to do is just pass the integer($user_id) within the function to be included in the SQL query.
So sorry to ask the question like this, but i am stuck now…

please help me, thanks a lot.

try this:
[php]

function getAllEvents($read, $user_id) {
global $user_id;
$sql = ‘SELECT * from events as e, invitations as i where e.event_id=i.event_id AND i.user_id= $user_id’;
return $read->fetchAll($sql);
}[/php]

Change your code to this:
[php]function getAllEvents($read, $user_id) {
$sql = ‘SELECT * from events as e, invitations as i where e.event_id=i.event_id AND i.user_id=’’.$user_id.’’’;
return $read->fetchAll($sql);
}[/php]

LOL a third option :smiley:
[php]
function getAllEvents($read, $user_id) {
$sql =“SELECT * from events as e, invitations as i where e.event_id=i.event_id AND i.user_id=’$user_id’”;
return $read->fetchAll($sql);
}
[/php]

Although that is an option, it is far easier to read and find occurrences of variables if you use concatenation (“string”.$variable.“more string”) rather than putting the variable in the middle of the string (“string $variable more string”).

I do believe in using concatenation but only when it is necessary
for example:
“select * from users where job=‘admin_’.$job”
I think if you are having to escape quotes to make the concatenation work because you used the same quotes to write the statement then there is probably a better way to write it, I don’t really think that ‘’.$user_id.’’ is easier to read than ‘$user_id’
another example:
‘select * from users where job=‘admin_’.’’.$job.’’ ’
starts looking pretty confusing doesn’t it?

In which case write:
[php] $sql = “SELECT * from events as e, invitations as i where e.event_id=i.event_id AND i.user_id=’”.$user_id."’";[/php]

No escaping of characters and the variable is easily separated from the strings.

Sponsor our Newsletter | Privacy Policy | Terms of Service