-2

I'm was trying to get my function to work and after a while I slammed my keyboard down and then everything worked and I noticed that:

{

function get_people_fullname($db, $people_id) {

$query = 'SELECT 
            people_fullname
        FROM 
            people
        WHERE
            people_id = '.$people_id;

$result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_assoc($result);
return $row['people_fullname'];}

}

where there query goes

people_id = '.$people_id;

which works

I originally had 

people_id = $people_id';

which doesn't work

I'm just lost and I think this is a simple thing someone more experienced can explain this to Me?

thanks

John Woo
  • 258,903
  • 69
  • 498
  • 492
Jake
  • 1
  • 1
  • 2
    [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ). – John Conde Feb 12 '13 at 02:20
  • Like @JohnConde noted above don't use MYSQL. I personally prefer PDO over MYSQLI due to named parameter support. –  Feb 12 '13 at 02:46

2 Answers2

3

you need to use double quotes in order to get the value of the variable,

$query = "SELECT 
            people_fullname
        FROM 
            people
        WHERE
            people_id = $people_id";

in php, let's say $a = 5,

echo 'a is $a'; // will result:        a is $s
echo "a is $a"; // will result:        a is 5

As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • Solid answer, also OP should not use mysql extension. It is being deprecated at 5.5 (which will hopefully be out soon) http://www.php.net/manual/en/function.mysql-connect.php You should be using the mysqli extension which is just as easy for a beginner to pick up as mysql, but is much more secure and allows for prepared statements – mr mojo risin Feb 12 '13 at 02:31
1

single quotes do not have variable substitution - double quotes is what you want if you want to replace $var with a value

Youn Elan
  • 2,379
  • 3
  • 23
  • 32