Rihards Egle
Rihards Egle

Reputation: 13

$_POST gives incorrect HTML input field value

I'am pissed at this code. Could someone explain where the problem is?

I have this HTML form:

<form action="item_add.php" method="POST" id="formadd">
    SKU: <input type="text" name="sku" id="form2"><br/>
    Name: <input type="text" name="name" id="form2"><br/>
    Price: <input type="text" name="price" id="form2"><br/>
    Type: <select name="type" id="form2">
        <option value="1">DVD-Disc</option>
        <option value="2">Book</option>
        <option value="3">Furniture</option>
    </select>
</form>

And this simple code for checking if everything works as I am new to this:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){//&&( isset( $_POST['submit1'] )){
    $item = new c_item;
    $item->$sku = mysqli_real_escape_string($link, $_POST['sku']);
    $item->$name = mysqli_real_escape_string($link, $_POST['name']);
    $item->$price = floatval(mysqli_real_escape_string($link, $_POST['price']));
    $item->$type = intval(mysqli_real_escape_string($link, $_POST['type']));

    echo "sku: ".$item->$sku."<br/>";
    echo "name: ".$item->$name."<br/>";
    echo "price: ".$item->$price."<br/>";
    echo "type: ".$item->$type."<br/>";
}

Problem is that it outputs me :

sku: Name

name: Name

price: 2

type: 2

when sku and price is inserted something different.

Upvotes: 1

Views: 78

Answers (1)

Robert
Robert

Reputation: 20286

Because you didn't paste whole code this will be just assumption

echo "sku: ".$item->$sku."<br/>";
            echo "name: ".$item->$name."<br/>";
            echo "price: ".$item->$price."<br/>";
            echo "type: ".$item->$type."<br/>"; 

there you execute dynamic name of variables so $name, can be the same as $sku and $price can be the same as $type

I don't know your c_item but probably what you want to do is declare in this class or something similar

class c_item 
{
    public $name;
    public $price, 
    public $sku;
    public $type;
}

and then in your code you need to use normal access to properties over dynamic with $

 $item = new c_item;

 $item->sku = mysqli_real_escape_string($link, $_POST['sku']);
 $item->name = mysqli_real_escape_string($link, $_POST['name']);
 $item->price = floatval(mysqli_real_escape_string($link, $_POST['price']));
 $item->type = intval(mysqli_real_escape_string($link, $_POST['type']));

 echo "sku: ".$item->sku."<br/>";
 echo "name: ".$item->name."<br/>";
 echo "price: ".$item->price."<br/>";
 echo "type: ".$item->type."<br/>";

notice lack of $ in property name of an object

Upvotes: 1

Related Questions