Exclude last comma in php array - php

I have a simple database connection:
$rowdata = mysql_query("SELECT * FROM table_names");
while($row = mysql_fetch_array($rowdata)) {
echo "".$row['name'].",";
}
I would like it to print out:
Adam, Sophia, Tom, Brian
instead of:
Adam, Sophia, Tom, Brian,
How do I exclude the last comma in the best way?

$rowdata = mysql_query("SELECT name FROM table_names");
$names = array();
while($row = mysql_fetch_array($rowdata)) {
$names[] = $row['name'];
}
echo implode(', ', $names);

Instead of echoing it straight out, put it into a variable (named $values perhaps) then do:
$values = rtrim($values,",");

Print the comma before each entry and omit the first one:
$first = TRUE;
while(($row = mysql_fetch_array($rowdata)) !== FALSE) {
if(!$first) echo ',';
echo htmlspecialchars($row['name']);
$first = FALSE;
}
Another way would be to use extract echoing the first line from the loop, that way the if statement does not have to be evaluated each iteration (premature optimization ftw!):
if(($row = mysql_fetch_array($rowdata)) !== FALSE)
echo htmlspecialchars($row['name']);
while(($row = mysql_fetch_array($rowdata)) !== FALSE) {
echo ',', htmlspecialchars($row['name']);
}

And finally you can do it in mysql:
select group_concat(name) from table_names
In full this would become:
$rowdata = mysql_query("SELECT group_concat(name) as names FROM table_names");
while($row = mysql_fetch_array($rowdata)) {
echo $row['names'];
}

$rowdata = mysql_query("SELECT * FROM table_names");
$names = array();
while($row = mysql_fetch_array($rowdata)) {
$names[] = $row['name'];
}
echo implode( $names, ',' );
By the way, if you're only using the 'name' column, it's better to do SELECT name FROM ..

Make it ..
$names = array();
while ( $row = mysql_fetch_array( $rowdata ) ) {
$names[] = $row['name'];
}
$names = implode(', ', $names);
echo $names;

Related

explode/implode from database php

I'm want string out of the column data.
But it failed.
<?php
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
$select_db = mysql_select_db("my_db", $conn) or die(mysql_error());
$select_tbl = mysql_query("SELECT * FROM log", $conn);
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (!isset($i[1])) {
for ($j = 0; $j <= 200; $j++) {
$i[$j] = null;
}
}
$name = $i[0];
$mama = $i[1];
$no = $i[2];
$a = $i[3];
$b = $i[4];
echo $name . "</br>";
echo $mama . $no . $a . $b . "</br>";
}
while ($data = mysql_fetch_object($select_tbl)) {
echo $data->data . "<br>";
}
?>
But i want output =
bus
car
bike
aabus
car
bike
aabus
car
bike
aabus
ddd
ee
And i not
Notice: Undefined offset: 3 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 21
Notice: Undefined offset: 4 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 22
Thank You.
You should just do what you want to do.
You want to connect to database then do it:
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
I suggest you to use mysqli library instead of mysql (mysql is deprecated in new php versions and totally removed in php7)
$conn = mysqli_connect("localhost", "nantawat", "12345678", "my_db") or die(mysql_error());
You want to query on log table, then do it:
$select_tbl = mysqli_query($conn, "SELECT * FROM log");
You want to fetch info from your result, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
echo $row['data'];
}
You want to explode data, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
$data = explode(',', $row['data']);
foreach ($data as $d) {
if ($d !== '') { // because before first comma or after last can be empty
echo $d . PHP_EOL;
}
}
}
If you want to save database result in variables:
If you are getting only one row of database, you can save them in variables directly:
$id_user = '';
$id_doc = '';
$date = '';
$data = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
}
And if you have multiple rows of database you need to save them all in a total array:
$array = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$data = array();
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
$array[] = array(
'id_user' => $id_user,
'id_doc' => $id_doc,
'date' => $date,
'data' => data,
);
}
And finally use this to see what structure your final array has:
echo '<pre>';
pront_r($array);
echo '</pre>';
First off it is not wise to store comma seperated values in a single cell and you are using deprecated mysql_ functions. I think your solution can be found in using a foreach instead of the isset part:
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
foreach ($i as $q){
echo $q . '<br/>';
}
}
If you still want to access your variables $name, $mama, $no and $ab, you can use isset for those specifically.
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (isset($i[0])){
$name = $i[0];
echo $name . '<br>'; //only echo if it exists
}
if (isset($i[1])){
$mama= $i[1];
echo $mama. '<br>'; //only echo if it exists
}
//try it yourself for $no and $ab
}
Try:
while ($row = mysqli_fetch_array($select_tbl)) {
extract($row);
/* Using extract method can get the array key value as variable
Below variables are available
$id_user;
$id_doc;
$date;
$data; */
}

Store data into array variable php

If i echo inside the while loop i get 4,2 values and if i echo outside the while loop then i only get 2. I want to get the data from $row into the values array. is something missing in this code?
$query = oci_parse($con, "SELECT count(*) FROM Counter GROUP BY Blog_name");
oci_execute($query);
while($row = oci_fetch_array($query))
{
$s = $row[0].',';
$values = explode(',', $s);
echo $values[0]; // 4
echo $values[1]; // 2
}
echo $values[0]; // 2
echo $values[1]; // 2
Try this,
$Values = array();
while($row = oci_fetch_array($query))
{
$Values[] = $row[0];
}
echo $Values[0];
First, $values as you're using it is just a string, and is not an array.
Try adding before the while loop.
$values = array();
Second, there's really no need to use explode here, it's an unnecessary step. If you only want the first column in the row, you can simply add that column to $values. (Currently you are overwriting the contents of $values at each iteration of the loop because you are missing the [].)
$values[] = $row[0];
If you're trying to put ALL of the columns in each row into values, try:
$values[] = $row;
If you're trying to individually put the contents of each column into it's own index in $values, try:
while($row = oci_fetch_array($query))
{
foreach($row as $column)
{
$values[] = $column;
}
}
Do like this:
$s = array();
while($row = oci_fetch_array($query)) {
$s[] = $row[0];
}
echo $s[0];
print_r($s);
$query = oci_parse($con, "SELECT count(*) FROM Counter GROUP BY Blog_name");
oci_execute($query);
$values = array();
while($row = oci_fetch_array($query))
{
$values[] = $row[0];
}
print_r($values);

trying to add seperator in alphabetically sorted list wen first letter will change

I sorted a list alphabetically and data from database mysql.To read the data i am using foreach loop.Now,I want when first letter (a->b->c) will change a seperator will be add after 'A' character list and so on.
Code:
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
foreach($result as $val){
echo $val['name']."<br>"; echo "<hr></hr>";
}
Thanks in advance
<?php
$first = '';
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
foreach($result as $val){
$first = substr($val['name'], 0, 1);
if ($first != $prev){
echo '<h1>'.$first.'</h1>';
}
echo $val['name']."<br>";
$prev = $first;
}
Try this:
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
$lastChar = "?"; //initialization
foreach($result as $val){
if($lastChar != $val['name'][0]){
echo $val['name'][0].'<BR>'; //separator
}
echo $val['name']."<br>"; echo "<hr></hr>";
$lastChar = $val['name'][0]; //update
}
Try this (untested code) :
$firstLetter = 'A';
foreach( $result as $val ) {
$ch = substr( $val['name'],1,1);
if( $ch != $firstLetter ) {
echo "<hr>";
$firstLetter = $ch;
}
echo $val['name']."<br>";
}
$char = 'a';
foreach($result as $val) {
$newChar = substr($val['name'],0,1);
if ($newChar != $char) {
$char = $newChar;
echo "seperator for new character";
}
//do your other stuff
}
Is this what you were wanting to do?

HTML select not inflating correctly from PHP array

I am trying to create a drop down menu of usernames or a <select> as it's known in HTML. However I am only getting the last value back from my array and I can't figure out why.
PHP
function getUserName($db) {
try {
$sql = 'SELECT members.name FROM members';
$query_an = $db->query($sql);
$count = $query_an->rowCount();
if ($count > 0) {
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names = array();
$names[] = $row['name'];
}
return $names;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
HTML
<select>
<?php $names = getUserName($db); foreach($names as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value ?></option>
<?php }?>
</select>
I'm fairly sure the HTML section of my code is solid. I think the error lies in how I'm adding values to my $names array but after staring at it for a half an hour I can't see it. Thanks for any help/fresh eyes.
You need to declare your array outside the loop
if ($count > 0) {
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
}
this is emptying your array every time : $names = array();
use this :
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
You are creating a new $names array every row then returning the last one. You need to declare the array outside the while loop. The following should work:
function getUserName($db) {
try {
$sql = 'SELECT members.name FROM members';
$query_an = $db->query($sql);
$count = $query_an->rowCount();
if ($count > 0) {
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
The problem is you're re-initializing the array on every loop:
See:
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names = array();
$names[] = $row['name'];
}
return $names;
Should be:
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;

Add string to all looped items except the last one

I'm looping through some mysql results and need to add <span id=bottom></span> to each of them except the last row. What's the easiest way of doing this?
Will I have to count rows and then use a counter and an if/else statement? Or is there an easier method?
Try something like this:
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_assoc($result))
{
$list[] = $row;
}
$lastItem = array_pop($list);
foreach($list as $item) {
echo sprintf('<span id="bottom">%s</span>', $item['value']);
}
// do something with the last item..
Not very short, but that would do the trick. Alternatively you could do what you suggested:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
for($i = 0; $i < $num-1; $i++) {
$element = mysql_fetch_assoc($result);
// echo here..
}
$item = mysql_fetch_assoc($result); // fetch last item..
Best wishes,
Fabian
I'm not a PHP expert, but can you put each row in an array? That way to know the length and you can loop through the array.
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_assoc($result))
$list[] = $row;
foreach(array_slice($list, 0, -1) as $item) {
echo sprintf('<span id="bottom">%s</span>', $item['value']);
}
// do something with the last item..
You can avoid copying all the data before processing it if you fetch a record in advance before printing it (or the other way round: process the previously fetched record)
foreach( $pdo->query('SELECT x FROM foo') as $r) {
if ( isset($row) ) {
echo '<span>', $row['x'], '</span>';
}
$row = $r;
}
if ( isset($row) ) {
echo $row['x'];
}

Categories