Add comma after value in Mysql PHP - php

I use below code,
$i = 0; $comma = NULL;
foreach($messages->get_logged_agents_dep(60) as $val_dep)
{
echo $department_id = $val_dep['department_id'].$comma;
}
I want to put comma (,) end of department_id (as I mentioned in $comma variable)
but last value should not put comma(,), because of I want to put above values in to SELECT * FROM tb_name WHERE IN (1,2,3) like this,
please help me to resolve this.
respect to your responds.
Thanks!

Try this :-
foreach($messages->get_logged_agents_dep(60) as $val_dep)
{
$department_id[] = $val_dep['department_id'];
}
echo $department_val = implode(",",$department_id);

You can also use rtrim()
$department_id = '';
foreach($messages->get_logged_agents_dep(60) as $val_dep) {
$department_id .= $val_dep['department_id'].',';
}
rtrim($department_id,','); // to trim last comma

Change your code to add the comma on the additional member of the sequence, not with.
$i = 0;
$comma = ',';
foreach(...)
{
echo ($i++>0)? $comma:'';
echo $department_id = $val_dep['department_id'];
}

Use implode(). See http://php.net/manual/en/function.implode.php
$i = 0; $arrIds = array();
foreach($messages->get_logged_agents_dep(60) as $val_dep)
{
$arrIds[] = $val_dep['department_id'];
}
echo implode(',', $arrIds);

Related

Remove Duplicated Entries From an Array

For removing the duplicated entries I know I have to use array_unique() but unfortunately by using this I got unexpected result(s). My PHP code is this:
$query = $db->query("
SELECT sid,father_contact,residential_contact
FROM ".TABLE_PREFIX."student_list
{$where_clause}
ORDER BY sid ASC");
while ($s = $db->fetch_array($query))
{
if (!empty($s['father_contact']))
{
$father_contact = $s['father_contact'].', ';
}
else
{
$father_contact = '';
}
if (!empty($s['residential_contact']))
{
$residential_contact = $s['residential_contact'].', ';
}
else
{
$residential_contact = '';
}
$phone_nums_bit .= $father_contact.$residential_contact;
}
This grabs all phone numbers from the database tables and print the result like this:
03334523675, 03124237009, 03134237002, 03124237009, 03217832173, 03134237002, 3134237002, 03124237009,
Notice that few numbers like 03134237002 is repeating thrice. I want to remove duplicate entries from this result. Please help me to sort it out. Thanks.
You can try to do it via array structures. Just to give you an idea:
$phones = [];
while ($s = $db->fetch_array($query))
{
if (!empty($s['father_contact']))
{
$phones[] = $s['father_contact'];
}
if (!empty($s['residential_contact']))
{
$phones[] = $s['residential_contact'];
}
}
$phones = array_unique($phones);
// and then combine into string
$phone_nums_bit = implode(', ', $phones);

Create a list like array when echoed in php

I would like to echo my results from a database and have them look like an array. They don't necessarily have to be an array but look like one. i.e. When i echo my result,
i would want my final result to look like
[10,200,235,390,290,250,250]
When i try the code below:
$query_rg = mysqli_query($link, "SELECT column FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma = "$list,";
echo ltrim($listwithcoma,',');
}
echo ']'
The result is :
[10,200,235,390,290,250,250,]
You are doing it wrong. ltrim($listwithcoma,',') has no effect.
ltrim — Strip whitespace (or other characters) from the beginning of a string
You can try a simple way with implode.
$list = array();
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column'];
}
echo '[' . implode(',', $list) . ']';
Just use GROUP_CONCAT in query as
$query_rg = mysqli_query($link, "SELECT GROUP_CONCAT(`column` SEPARATOR ', ') as data
FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
print_r($row_rg['data']);
Try like this
$list = array(); //define a array.
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column']; //store column value in array.
}
$lists = "[".implode(",",$list)."]";
echo $lists; //will echo your results.
You should be using rtrim() function instead, that too outside the loop.
$listwithcoma = '';
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma .= "$list,";
// echo ltrim($listwithcoma,','); Remove this
}
echo rtrim($listwithcoma,','); // Add this
echo ']';

Add space in String

I would like to add space during string assignment like:
$movie_genre.= $row["movie_genre"]." ";
where it should display genre1 genre2 genre3 and so on. Single space between these three genres is required. Currently it is showing genre1genre2genre3
Collect it in an array & then use implode:
{// your loop starts
$movie_genre[] = $row["movie_genre"];
}//// your loop ends
echo implode(" ", $movie_genre);
#MuhammadMuazzam,Please check below code.
//Suppose your data array like below.(Below is sample example)
$dataArray = array('data1','data2','data3');
$numItems = count($dataArray);
$i = 0;
$movie_genre = '';
foreach($dataArray as $value)
{
if(++$i === $numItems) {
$movie_genre.= $value;
} else {
$movie_genre.= $value." ";
}
}
echo $movie_genre;
Your existing code is perfect,
just add a single line rtim()
$movie_genre.= $row["movie_genre"] . " ";
$movie_genre = rtrim($movie_genre);

how to get individual element from array in php?

I have dateValues as follows,
[dateVals] = 031012,041012;
it is comma seperated values. I want to make this as array and to get individual values . As i am new to PHP , i want some one's help .
$val = array[dataVals];
for($i=0;$i<sizeof($val);$i++) {
echo "val is".$val[$i]."\n";
}
is not working
use this code
$dateVals = '031012,041012';
$pieces = explode(",", $dateVals);
for($i=0;$i<sizeof($pieces);$i++) {
echo "val is".$pieces[$i]."\n";
}
it will give you proper output.
working example http://codepad.viper-7.com/PQBiZ3
$dateVals = '031012,041012';
$dateValsArr = explode(',', $dateVals);
foreach( $dateValsArr as $date) {
}
Try this code.
Try this One
$dateVals = '031012,041012';
$date_arr[] = explode(',',$dateVals);
for($i = 0 ; $i < count($date_arr) ; $i++)
{
print $date_arr[$i].'<br />';
}

PHP foreach loop

I have the array example below that I am using to dynamically create an SQL query based on the options ticked in a form. The code below tests whether there is a value, if so, append it to the array:
if ($lookchild) { $val[]='lookchild'; }
if ($mentalcap) { $val[]='mentalcap'; }
if ($mentalheal) { $val[]='mentalheal'; }
if ($olderpeople) { $val[]='olderpeople'; }
if ($palcare) { $val[]='palcare'; }
I am then looping through the array and adding the rest of the SQL statement:
foreach ($val as $r){
echo $r.'=1 AND ';
}
This produces:
olderpeople=1 AND palcare=1 AND lookchild=1 AND
When the loop reaches the last entry, I don't want it to append the AND to it as the SQL statement needs to close after that point.
How I want it to complete:
olderpeople=1 AND palcare=1 AND lookchild=1
Implode
In these situations you can use implode
It 'glues' an array together.
implode ( string $glue , array
$pieces )
Example:
echo implode('=1 AND ', $val);
echo '=1';
A common trick is to use 'WHERE 1=1' then you can append ' AND foo = bar' without a syntax error.
WHERE 1=1 AND olderpeople=1 AND palcare=1 AND lookchild=1
This is what implode() is for:
$result = array();
foreach ($val as $r){
$result[] = "$r=1";
}
$result = implode($result, ' AND ');
Live Example
Just don't print the AND for the last value of the foreach loop. Here is the code to use:
foreach ($val as $r){
echo $r.'=1';
if (next($val)) {
echo ' AND ';
}
}
use the implode function
$sql = implode("=1 AND ", $array)."=1";
and you wont have to use a for loop :)
Instead on assigning palcare to $val[], assign $val[] = "palcare = 1" etc. Them
implode(" AND ", $val);
Try this :
$isFirst = true;
foreach ($val as $r){
if(!$isFirst){
echo ' AND ';
}else{
$isFirst = false;
}
echo $r.'=1';
}
I would remove the last 4 characters of the string with:
$r = '';
foreach ($val as $r){
$r.'=1 AND ';
}
$r = substr($r, 0, -4);
echo $r;
Checkout http://ca3.php.net/manual/en/function.substr.php, quick and easy
If you have to do it with a foreach (and for some reason you cant use implode, which is a good suggestion) you will need a way to keep track of where you are.
I thought to add the "AND" before anything but the first item, instead of adding it after anything but the last item, something like this:
$sqlwhere = "";
foreach ($val as $r){
if($sqlwhere ==""){
$sqlwhere = $r;
}
else {
$sqlwhere .= " AND " . $sqlwhere;
}
}
echo $sqlwhere;
I used a varable instead of just echoing it out too, which I find useful in complicated sql statements anyway.
Use implode. But if for some reason you need to loop (such as you need to do more logic than just joining the strings), use a separator approach:
$seperator = '';
$result = '';
foreach ($array as $value) {
// .. Do stuff here
$result .= $seperator . $value;
$seperator = ' AND ';
}
The benefit is both brevity and flexibility without checking conditions all the time...
Since you are using an array, you can also use count to figure out how many are in the array and if you are on the last item, don't append the 'AND'.
$result = array();
$totalcount = count($val);
$currentCount = 0;
foreach ($val as $r){
$currentCount ++;
if ($currentCount != $totalcount){$result[] = "$r=1 AND ";}else{$result[] = "$r=1";}
}

Categories