Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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

share|improve this question

marked as duplicate by mario, John Conde, jeroen, Jocelyn, tereško Feb 12 '13 at 23:32

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2  
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial. –  John Conde Feb 12 '13 at 2:20
    
Like @JohnConde noted above don't use MYSQL. I personally prefer PDO over MYSQLI due to named parameter support. –  David Eugene Peterson Feb 12 '13 at 2:46

2 Answers 2

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.

share|improve this answer
    
Solid answer, also OP should not use mysql extension. It is being deprecated at 5.5 (which will hopefully be out soon) 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 2:31

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

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.