php foreach comparison problem

Fark_Maniac

2[H]4U
Joined
Feb 21, 2002
Messages
2,438
Below is the meat of the code of what I'm trying to accomplish. What I'm doing is editing data base content from a form. The form passes all data as POST, I retrieve the old information and compare the two. If the data was changed, then I will (eventually) build a string that I will use to update just the fields that were changed.

I've done some googling and found out about the foreach($res as $key => $db_value) thing and thought it was pretty slick way of getting this accomplished. What is not working is the ($value != $_POST['$key']) comparison. My output states that all values have changed. Following the code is an output of what I get.

PHP:
$sql = "select isbn, title, author, backing, series_num, fin, comments, book_type from bookinfo where ISBN = '$_POST[isbn]'";
		$res = mysql_fetch_assoc(mysql_query($sql,$conn));
        $build = "";
        $point = 0;
		$count = 0;

        foreach($res as $key => $db_value)
        {   $esc = mysql_real_escape_string($_POST[$key]);
			if(($db_value != $_POST['$key'])&&($point==0))
            {   //If the value of key does not equal what was passed and this is the first, start building the query
                //$build .= "$key=$esc";
				echo "<strong>Key:</strong> $key &nbsp;<strong>Value:</strong> $db_value &nbsp;<strong>Post:</strong> $_POST[$key] <em><strong>First</strong></em><br>";
                $point++;
            }
            elseif(($db_value != $_POST['$key'])&&($point>0))
            {   //If the value of key does not equal what was passed and this is the second edit, continue building query statement
                //$build .= ",$key=$esc";
				echo "<strong>Key:</strong> $key &nbsp;<strong>Value:</strong> $db_value &nbsp;<strong>Post:</strong> $_POST[$key]<br>";
            }
			$count++;
        }

Key: isbn Value: 0-8041-1998-8 Post: 0-8041-1998-8 First
Key: title Value: Phantom Warriors: Book One Post: Phantom Warriors: Book One
Key: author Value: Gary Linderer Post: Gary Linderer
Key: backing Value: soft Post: soft
Key: fin Value: yes Post: yes
Key: comments Value: Book one of a Vientam LRRP, LRP, and Ranger series Post: Book one of a Vientam LRRP, LRP, and Ranger series. EDIT
Key: book_type Value: viet Post: viet
 
actually, I've found what was happening:
$_POST['$key']

should have been

$_POST[$key]

because $key was already a string type and does not need to be quoted.
 
fwiw, $_POST["$key"] would have worked as opposed to $_POST['$key'] with the single quotes, the single quotes do not do variable substitution. you should not use "$var" when $var by itself would do in this case. practically i'm sure you won't notice any performance hit but theoretically there is extra overhead from having to parse the string for variable substitution.

see http://us2.php.net/string
 
Back
Top