Jump to content

How do I loop part of a value


lorddemos90

Recommended Posts

Here is the code for the value "str"

$str = "<?xml version='1.0'?>
<properties>
<?php do {<property>
<city>$city</city>
</property>}
while ($row_rscontacts = mysql_fetch_assoc($rscontacts));?>
</properties>";

What I want to do is loop everything within the <property> tags for each table row in the mysql database.  I tried inserting a loop as you can see, but it's just taking my code as literal text and not actually processing it.  So how is this done?  I'm a beginning programmer so please make sure to explain all code that is typed.
Link to comment
https://forums.phpfreaks.com/topic/30342-how-do-i-loop-part-of-a-value/
Share on other sites

You could use this code:

[code=PHP]<?php

$str = "<?xml version='1.0'?>\n
<properties>\n";

while ($row_rscontacts = mysql_fetch_assoc ($rscontacts))
{
      $str .= "\t<property>\n
            \t\t<city>{$city}</city>\n
            \t</property>\n";
}

$str .= "</properties>";

?>[/code]

[b]Note:[/b] There is a "." (dot) in the while loop and at the last [b]$str[/b] before the "=" sign, this means the values are appended to the current string and the value is not overwritten.
$str [b][color=red].[/color][/b]=

I've also changed the loop a bit, added the while clause on top to make sure it writes something only if you have some values.

Boby
Here is a more detailed example, make sure the SQL query is correct and I've also noticed you are using [b]$city[/b] but the variable was not assigned. Use [b]$row_rscontacts['db_table_field'][/b], in the  following example it's [b]$row_rscontacts['city'][/b].

[code=PHP]<?php
//Build SQL query
$sql = "SELECT `city` FROM `db_users`";
//Run SQL query
$rscontacts = mysql_query ($sql);
//Check if query was successfull
if (!$rscontacts)
{
  echo "Could not successfully run query ({$sql}) from DB: " . mysql_error();
  exit;
}

$str = "<?xml version='1.0'?>\n
<properties>\n";

//Check if we have results
if (mysql_num_rows ($rscontacts) > 0)
{
  //Loop through each found row
  while ($row_rscontacts = mysql_fetch_assoc ($rscontacts))
  {
      $str .= "\t<property>\n
            \t\t<city>".$row_rscontacts['city']."</city>\n
            \t</property>\n";
  }
}

$str .= "</properties>";

?>[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.