-1

I am writing a script to access a specific detail about the user and I was hoping to make the database query be function.

function connectUser($ip) {
   $q = "SELECT * FROM users where ID='$ID'";
   $s = mysql_query($q);
   $r = mysql_fetch_array($s);
}

But when I try and use it it will not access the row the way I want it to.

$user = '999';
connectUser($user)
echo $r['name'];

But if I put echo $r['name']; in the function it will work.

Tiny
  • 209
  • 1
  • 6
  • 18

4 Answers4

1

your function is not returning anything. add return $r['name'] at the end of function.
then echo connectUser($user);

Jigar Tank
  • 1,654
  • 1
  • 14
  • 24
1

thare are 2 major problems in your code

  1. the function doesn't return anything and you don't assign it's result to a variable.
  2. Your variables doesn't match. $ip doesn't seem the same variable with $ID

so, this one would work

function connectUser($id) { 
   $q = "SELECT * FROM users where ID=".intval($id); 
   $s = mysql_query($q); 
   return mysql_fetch_array($s); 
} 

$user = '999'; 
$r = connectUser($user) 
echo $r['name']; 
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

That's because the variable $r isn't being returned by the function, so it's never being set outside of the function. Here's what you should have:

function connectUser($ip) {
   $q = "SELECT * FROM users where ID='$ip'";
   $s = mysql_query($q);
   return mysql_fetch_array($s);
}

And then outside have:

$user = '999';
$r = connectUser($user)
echo $r['name'];

You might also want to take a look at this question: prepared statements - are they necessary

Community
  • 1
  • 1
EdoDodo
  • 8,220
  • 3
  • 24
  • 30
  • Thanks that worked perfectly. Also I realize that I was serving the variable called $ip which was a mistake when writing this post. It didn't cause an issue on my code. – Tiny Dec 10 '11 at 08:28
0

This function is not working,
as you did not supplied the database connection into function,
and you did not return anything (PHP will return NULL)

Please understand what is variable scope first,
and the function

A workable example, can be like :-

function connectUser($db, $ip) 
{
  $q = "SELECT * FROM users where ID='$ID'"; // vulnerable for sql injection
  $s = mysql_query($q, $db);                 // should have error checking
  return mysql_fetch_array($s);              // value to be returned
}

How to use :-

$db = mysql_connect(...);
$res = connectUser($db, "some value");
ajreal
  • 46,720
  • 11
  • 89
  • 119
  • The database was already connected and as I mentioned it worked when the function was echoing the variable. – Tiny Dec 10 '11 at 08:24