Page 1 of 1

Syntax error on echo that displays assoc array

Posted: Mon Mar 28, 2016 8:46 am
by tcarp
PHP beginner. Statement comes from code that is initializing a MySQL db. I use the echo's to help me with testing.

Had things working before I needed to convert to MySQLi. Couldn't find a direct replacement for mysql_result so moved to mysqli_fetch_assoc.

The old technique created a variable for each field which a coded echo "<br> $field1 $field2 $field3".

The new technique creates an assoc array. The best I've been able to figure is an echo like this:

$row=mysqli_fetch_assoc($result) or die(mysql_error());

echo "{$row['Locationnum'] {$row['Neighborhood'] $row['Udate']} </b><br> {$row['Address1'] $row['Address2'] $row['City'] $row['State'] $row['Zip'] $row['Owner'] $row['Status'] $row['Gas'] $row['Water'] $row['Electricity'] $row['Fire'] $row['Residents'] $row['Phone1'] $row['Description1'] $row['Phone2'] $row['Description2'] $row['Phone3'] $row['Description3'] $row['Resourceskill'] $row['Resources']} <br> {$row['Skills'] $row['Needs']} <br><br>";


The syntax error is with the braces needed to identify the variables. To put them in for all the variables is tedious, although the syntax error gets resolved. Is there a better way to display all the fields in a record via echo?

Re: Syntax error on echo that displays assoc array

Posted: Mon Mar 28, 2016 3:09 pm
by requinix
Don't nest the {}s. Use one pair for each value.

Code: Select all

echo "{$row['Locationnum']} {$row['Neighborhood']} {$row['Udate']}...";

Re: Syntax error on echo that displays assoc array

Posted: Mon Mar 28, 2016 5:16 pm
by Christopher
Yes, braces within double quoted strings instruct the parser to parse all the way to the closing brace. Without the braces in the line above, the parser would only find $row because [ is not a valid character in variable names. Use braces when specifying array elements and object properties in double quoted strings.

Re: Syntax error on echo that displays assoc array

Posted: Mon Mar 28, 2016 5:43 pm
by requinix
As for
tcarp wrote:To put them in for all the variables is tedious, although the syntax error gets resolved. Is there a better way to display all the fields in a record via echo?
Not really. At least not when you want certain values to appear in different locations in the markup.

And actually, there's a good chance that in the future you'll want to format that all differently anyways. All the values together as they are now won't look very nice.

Re: Syntax error on echo that displays assoc array

Posted: Tue Mar 29, 2016 1:47 pm
by Christopher
tcarp wrote:Is there a better way to display all the fields in a record via echo?
If you just want to display the values of an array with the same markup in between, you can do something like this:

Code: Select all

echo "<div>" . implode("</div><div>", $row) . "</div>";