1

I'm trying to grab a name from a database and then created a textfield with the value preset to that name. I'm creating the textfield by echoing it out with php and setting the value to the name. However the variable i put in the value is not running it's just printing out as {$c->prod_name} instead of the actual name.

Here is my query:

function name_id($id) {
    global $pdo;

    $stmt = $pdo->prepare("
        SELECT prod_name
        FROM products
        WHERE id = '$id'
        LIMIT 50");

    $stmt->execute();

    return $stmt->fetchAll( PDO::FETCH_OBJ );   
}

Here is where i echo out the text field:

<?php

    $name = name_id($id);

    foreach($name as $c){

        echo '<input name="prod_name" type="text" size="50" value="{$c->prod_name}" ?>';

    }

?>

3 Answers 3

1

Two glitches in your code

Addressing your problem: it's just printing out as {$c->prod_name}:

For your echo statement you use single quotes '. Variables and escape sequences (other than \' and \\) are not expanded inside single quotes. That means, the $ and {} have no special meaning and are outputted as plain text, not as variable (see doc). You need to move the variable out of the string and use concatenation if you want to use single quotes, like that:

echo '<input name="prod_name" type="text" size="50" value="' . {$c->prod_name} . '" ?>';

Glitch #2 in your name_id function: Change the lines to the following:

$stmt = $pdo->prepare("
    SELECT prod_name
    FROM products
    WHERE id = ?
    LIMIT 50");

$stmt->execute(array($id));

If you are importing the variable into the prepare string, you are not preventing XSS attacks, etc. - see php.net PDO::prepare for more information.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @lazyhammer for his suggested edit. I don't know why it was rejected as it improves my answer a lot.
0

replace all occurences of single quotes ' with double "

and vice versa

change this :

  echo '<input name="prod_name" type="text" size="50" value="{$c->prod_name}" />'; ?>

to this:

echo "<input name='prod_name' type='text' size='50' value='{$c->prod_name}'/>"; ?>';

Comments

0

The "echo-ing" of a variable in a string statement like this only works with " (double qoutes). Therefore, you could escape a lot of the double quotes like so:

echo "<input name=\"prod_name\" type=\"text\" size=\"50\" value=\"{$c->prod_name}\">"; ?>

but it is so much easier to just concatenate the string like so:

echo '<input name="prod_name" type="text" size="50" value="'.$c->prod_name.'">'; ?>

The simplest answer is: when you "inline" a variable it MUST be in double quotations:

echo "{$c->prod_name}";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.