gets rid off the delimiter
hi i have got the following issues i am using the following code.
<?php
//DB CONNECTION
$ROWS = "id,firstname,lastname";
// explode at the comma and insert into an array
$test = explode("," , $ROWS);
//adds array test to the var sam
$sam = array($test);
// querys the database
$new = mysql_query("SELECT * FROM {$DB_TABLE}");
// while loop to loop through selected fields
while ($row = mysql_fetch_array($new)) {
foreach ($sam[0] as $v) {
echo $row[$v] . $DELIMITER . "<br />";
}
echo "<br />";
}
?>
This will output the following .
834(|)Step(|)Thompson(|)
835(|)Lucy(|)kim(|)
836(|)Iwan(|)Will(|)
837(|)Sarah (|)Good(|)
what i am struggling with is i want to get rid off the last delimiter
so it would be
834(|)Step(|)Thompson
835(|)Lucy(|)kim
836(|)Iwan(|)Will
837(|)Sarah (|)Good
i have tried using
// while loop to loop through selected fields
while ($row = mysql_fetch_array($new)) {
foreach ($sam[0] as $v) {
$test = $row[$v] . $DELIMITER;
echo substr($test, 0, -1);
}
echo "<br />";
}
but this gets rid off the delimiter for all off them???
This will output the following .
834Stephompson
835Lucykim
836IwanWill
837SarahGood
ideally i would开发者_JS百科 like each row to be its own stored together.
Any Help Please i am having a bad day today my head is fried completely???
Try using implode :
while ($row = mysql_fetch_array($new)) {
$myrows = array();
foreach ($sam[0] as $v) {
myrows[] = $row[$v];
}
echo implode($DELIMITER, $myrows).'<br />';
}
Method 1: Write the data of each row into an array, and then use implode
Method 2: set a flag to omit the delimeter once;
<?php
while (...)
{
$tmp = 1;
foreach (...)
{
if ($tmp)
{
$tmp = 0;
}
else
{
echo $DELIMETER;
}
echo $row[...];
}
}
You can try something like this
// querys the database
$new = mysql_query("SELECT * FROM {$DB_TABLE}");
// while loop to loop through selected fields
while ($row = mysql_fetch_array($new)) {
echo $row[0];
for($i = 1; $i < count($row); $i++) {
echo $DELIMITER.$row[$i];
}
echo "<br />";
}
Thanks for all the responses people manage to get it to work with the following ;)
// querys the database
$new = mysql_query("SELECT {$ROWS} FROM {$DB_TABLE}");
// while loop to loop through selected fields
while ($row = mysql_fetch_assoc($new)) {
$tmp = array();
$tmp[] = implode($DELIMITER, $row);
echo $tmp[0] . "<br />";
}
You could insert into an array (denoted as the alternative way) the values you need and avoid the foreach for each row you get from database but if you really want to use the code as you got it now you can do the following:
while ($row = mysql_fetch_array($new)) {
$values = array();
foreach ($sam[0] as $v) {
$values[] = $row[$v];
}
echo implode($DELIMITER , $values) . '<br/>';
}
or the alternative
while ($row = mysql_fetch_array($new)) {
$values = array($row['id'], $row['firstname'], $row['lastname']);
echo implode('(|)',$values) . '<br/>';
}
精彩评论