Remove last comma from array after obtaining database results - php

I'm trying to list data from my database, and I need to use variables inside of my array, but when echoing it I want it to remove the last comma but it doesn't seem to work.
$forum_usersonline = $kunaiDB->query("SELECT * FROM users WHERE user_loggedin = '1'");
while($forum_usersonline_fetch = $forum_usersonline->fetch_array()) {
$usersonlineuname = $forum_usersonline_fetch["user_name"];
$onlinelist = array($usersonlineuname, ' ');
echo implode($onlinelist, ',');
}
It always returns with user1, user2, so how should I do it?

Your can do this job easily in sql. If your database is mysql try following
SELECT GROUP_CONCAT(user_name) as user_name FROM users WHERE user_loggedin = '1'
or if your database is postgres try following
SELECT string_agg(user_name, ',') as user_name FROM users WHERE user_loggedin = '1'
above query result return comma separated user_name.

You could use chop(); which removes characters from the right end of a string.
An example:
<?php
$str = "Random String Ending With,";
echo $str . "<br>";
echo chop($str,",");
?>
Or you could use rtrim(); like:
<?php
$str = "Random String Ending With,";
echo $str . "<br>";
echo rtrim($str,',');
?>
Or you could also use substr like:
<?php
$str = "Random String Ending With,";
echo substr($str,0,-1)."<br>";
?>

use rtrim(string,',')
For reference goto http://www.w3schools.com/php/func_string_rtrim.asp

The problem is you're doing the implode inside the while loop, it should be done outside after building your final array. This is what I would do:
$forum_usersonline = $kunaiDB->query("SELECT * FROM users WHERE user_loggedin = 1");
while ($row = $forum_usersonline->fetch_array()) {
$onlinelist[] = $row["user_name"];
}
echo implode($onlinelist, ",");
However, this should not be the case as you should be using CONCAT when doing your database query.

Related

PHP query with string contain quotes

Hi i need to do a request to mysql to get some data where filed name = $letter
but the variable $letter may contain '
my problem is this i try to use this :
$letter = mysqli_real_escape_string($conn,strtolower($letter));
$us = $conn->query("SELECT id FROM singers where trim(LOWER(name)) = '".$letter."'");
My problem is in if $letter was I'm legend, after executing this line it become I\'m legend so it can't be find in database because in database it's stored as i'm legend
how i can resolve this and get right result.
echo $letter;
$letter = mysqli_real_escape_string($conn,strtolower($letter));
echo $letter;
RESULT
i'm
i\'m
why you have used
trim and LOWER in your column name
"SELECT id FROM singers where trim(LOWER(name)) = '".$letter."'" //why trim and LOWER
use this
"SELECT id FROM singers where name = '".$letter."'"
Also try this like
$letter = mysqli_real_escape_string($conn,strtolower($letter));
$sql = "SELECT id FROM singers where name = '".$letter."'";
// echo $sql; die; print this and run in phpmyadmin to check
$us = $conn->query($sql);
if ($us !== false) {
echo 'done';
}
else{ die('failed!' . mysqli_error($conn));}
there is difference between field and value in where
the \ added is the problem

Formatting output from mysql (array of values)

I am running a sql query to output value of field, which has array of values. How can I format those value using php/css/html.
This is the output I get from following code:
$rb = $wpdb->get_results("select value
from wp_rg_lead_detail
where field_number = 33
and lead_id =
(select distinct lead_id
from wp_rg_lead_detail
where value = '".$uname."')
");
foreach( $rb as $r){
echo $r->value . "<br/> ";
}
MySQL Output Value:
a:2:{
i:0;a:2:{s:10:"First Name";s:6:"testb1";s:9:"Last Name";s:5:"test1";}
i:1;a:2:{s:10:"First Name";s:6:"testb2";s:9:"Last Name";s:5:"test2";}
}
Desired Output:
FirstName LastName
testb1 test1
testb2 test2
Can someone help me with this?
To start, you'll need to remove the new lines and tabs from your serialized data before it will unserialize() correctly:
$data = unserialize('a:2:{i:0;a:2:{s:10:"First Name";s:6:"testb1";s:9:"Last Name";s:5:"test1";}i:1;a:2:{s:10:"First Name";s:6:"testb2";s:9:"Last Name";s:5:"test2";}}');
You can output the results you want with a simple loop like this:
// Keep track of whether the headers have been output yet
$headersOutput = false;
foreach ($data as $row) {
// If the headers haven't been output yet
if (!$headersOutput) {
// Output the headers only
echo implode("\t", array_keys($row)), PHP_EOL;
// Update variable so it won't happen again
$headersOutput = true;
}
// Output the values
echo implode("\t", array_values($row)), PHP_EOL;
}
Example:
First Name Last Name
testb1 test1
testb2 test2
You can swap the "\t" tab characters for whatever you want to delimit columns with, and swap PHP_EOL for what should delimit new lines.
If you want to add this data to an array (e.g. to write to a CSV instead) then just use $output[] = implode... instead of echo and use $output at the end.

Pass PHP Variable into WHERE/AND MySQL Query

I'm trying to pass a value for a query that takes in a variable from an earlier Sql query and then compares the result against a field from another table. But I can't seem to figure out my syntax.
$topName = $row_rsAdminDetails['fullName'] ;
$TESTqueryTwo =
"SELECT * FROM participants, admin WHERE admin.over_id = participants.fk_over_id AND participants.dr_over_names LIKE '%$topName%'";
$TESTresult2 = mysql_query($TESTqueryTwo) or die(mysql_error());
the php output I'm looking to do:
<?php
// Print out the contents of each row
while($row_TESTresultTwo = mysql_fetch_array($TESTresultTwo)){
echo $row_TESTresultTwo['userName']. " - ". $row_TESTresultTwo['Participant_Name'];
echo "<br />";
}
?>
Problem could be on this line:
while($row_TESTresultTwo = mysql_fetch_array($TESTresultTwo)){
should be
while($row_TESTresultTwo = mysql_fetch_array($TESTresult2)){
// as you have no $TESTresultTwo variable...
}
And also try with the query ... with LIKE '%".$topName."%'"

Where IN Clause in PHP & output of while loop outside of while

My Php code is
<?php
include('session.php');
include('db.php');
$session=$_SESSION['agent'];
$home1 = "SELECT fullname FROM users WHERE role='$session'";
$result1=mysql_query($home1) or die(mysql_error());
while ($row1=mysql_fetch_array($result1)) {
echo $gallery = "'".$row1[0]."',"; // output is 'sam','teja','multiplevaluessoon',
$home = "SELECT * FROM chat WHERE chat.from IN ('$gallery')";
}
$result=mysql_query($home) or die(mysql_error());
while ($row=mysql_fetch_array($result)) {
$msg =$row["message"];
echo $randomUserId=$row["from"];
echo $msg . "<br/>";
}
?>
here $gallery contains ',' comma at the end, so i am getting a error in where clause, when i am trying to trim the output of $gallery
'sam','teja','multiplevaluessoon',
last charcter inside loop i am getting
'sam''teja''multiplevaluessoon'
which is trimming all the commas due to while loop, i need last comma to be trimmed so that i can execute it in where clause
please suggest me any ideas
Make use of rtrim().
$yourfinaltext = rtrim($yourcommadelimitedstring, ',');
Change your while like this.
while ($row1=mysql_fetch_array($result1)) {
$gallery .= "'".$row1[0]."',";
$home = "SELECT * FROM chat WHERE chat.from IN ('$gallery')";
}
echo rtrim($gallery,',');
$rest = substr("abcdef", 0, -1); // returns "abcde"
http://php.net/manual/en/function.substr.php
Remove comma as this...
$gallery=substr_replace($gallery ,'',0,1);

Heep needed with str_replace

I face a problem with the str_replace function, see the code below :
$query = "SELECT title FROM zakov WHERE chnt='$atd_nad'";
$str = str_replace("Example.com_", "","$query");
$result = mysql_query($str) or die('Errant query: '.$str);
What I want is to replace the word " Example.com_ " with nothing "" but it did not work for me ! I do not know why.
In the row 'title' you can find something like this " Example.com_nameofsmthng "
So what I want is to keep just the word "nameofsmthng" and also to keep the begining of each word of it in capital letter to have finally somethin like "NameOfSmthng"
$atd_nad = 'Foobar Example.com_nameofsmthng Bazbat';
$query = 'SELECT title FROM zakov WHERE chnt="' . $atd_nad . '"';
$str = str_replace('Example.com_', '', $query);
echo $str; // SELECT title FROM zakov WHERE chnt="Foobar nameofsmthng Bazbat"
This works fine. Try it quickly. My assumption is that you mistyped $atd_nad or the value is incorrect.
Edit: hmm i think I misunderstood the example your trying to replace the string in the query string instead of the database?
You could make mysql do the replacement for you which should be faster then making php do it.
$query = "SELECT REPLACE(title, 'Example.com_', '') as newtitle FROM zakov WHERE chnt='$atd_nad'";
$resultset = mysql_query($query) or die('Errant query: '.$query);
$result = mysql_fetch_assoc($query);
echo $result['newtitle'];
Or you could replace all occurrences in the database with an update and then just select the title.
UPDATE zakov SET title = REPLACE(title, 'Example.com_', '');
Hope this helps.
while($row = mysql_fetch_assoc($result)) {
$title = str_replace("something", "", $row['title']);
}
Is what I believe you're looking for. Your code is trying to replace it in the query, which doesn't make sense. You need to replace it in the actual records. This will replace "something" with "". Alternatively, if you've already stored them in an an array or something you would just loop over the array and do the replacement. Basically: operate on the records, not on the query.

Categories