hope you can help, tearing my hair out here!
I have...
$result = mysqli_query($con,'SELECT this FROM that');
while($row = mysqli_fetch_array($result))
{
echo $row['this'] . ',';
}
Which returns...
222,225,243,256,260,269,273,280,295,296,
I need to remove the last comma to give me just...
222,225,243,256,260,269,273,280,295,296
I've tried trim rtrim substr and everything else I could find but none of them work. Think it's to do with the concatenation of the $row['this'] . ',' but I cant figure out how to resolve it!
Any help would be appreciated.
Cheers,
Mark.
Just let MySQL do the work for you:
$result = mysqli_query($con, 'SELECT GROUP_CONCAT(this, ',') as thises FROM that');
This constructs the results as a comma-delimited string. You can refer to it by its name, thises.
Use rtrim to remove last comma.
rtrim($my_string,',');
you can use implode
while($row = mysqli_fetch_array($result))
{
$a[]= $row['this'];
}
$b = implode(',',$a);
print_r($b);
function for implode
function imp($c){
$d= implode(',',$c);
return $d;
}
$b = imp($a);
print_r($b);
You can use substr()
This is your code
$result = mysqli_query($con,'SELECT this FROM that');
while($row = mysqli_fetch_array($result))
{
echo $row['this'] . ',';
}
Code Should like this
$result = mysqli_query($con,'SELECT this FROM that');
$my_string = "";
while($row = mysqli_fetch_array($result))
{
$my_string .= $row['this'] . ',';
}
$my_final_string = substr($my_string, 0, strlen($my_string)-1);
echo $my_final_string;
Explanation
substr(string,start,length)
string = Your generated string
start = From which position you want to start the string.
length = A positive number - The length to be returned from the start parameter. Negative number - The length to be returned from the end of the string
Related
I have a mysql table(request) here:
request:
r_id item_no
1 1
13 10
22 20
33 30
55 40
Now, I'm using php to take r_id out using mysql_fetch_array() and try to put mysql_fetch_array() result in to a string also split the string by comma.
<?php
include('config.php'); //connect to mysql
function f(){
$sql = "SELECT r_id FROM `request` ";
$result=mysql_query($sql);
$string = '';
$i = 0;
while ($row = mysql_fetch_array($result)) {
$string .= $row[$i];
}
$newstring = implode(", ", preg_split("/[\0-9]+/", $string));
return $newstring ;
}
$get=f();
echo $get;
?>
But I cannot get the right string form my php code.
I want to get the string like
1,13,22,33,55
How can I fix the problem?
You don't need to split that and implode, just do this:
while ($row = mysql_fetch_array($result)) {
$string .= $row[$i].',';// append comma after each value you append to the string
}
return substr($string,0,-1);// cut off the trailing comma from the final string
<?php
include('config.php'); //connect to mysql
function f(){
$sql = "SELECT GROUP_CONCAT(r_ID) FROM `request` ";
$result=mysql_query($sql);
return $result ;
}
$get=f();
echo $get;
?>
Try my updated answer:
$sql = "SELECT r_id FROM `request` ";
$result=mysql_query($sql);
$string = '';
$i = 0;
while ($row = mysql_fetch_array($result)) {
$string .= $row[$i].",";
}
return $string ;
}
$array = array();
while(...){
$array = $row[$i]; //first you need array
}
$string = implode(",",$array); //now you have your string
In my database table there is a column named 'marks' . it contains values like 50,55,67,88,...
Now I need to read this values one by one like - first 50, then 55 and so on. How is it possible using php ?
include("db_connect.php");
$result = mysql_query("SELECT * FROM students ",$con);
while($rows = mysql_fetch_array($result))
{
$mark1=$rows['marks'];//what will do here
$mark2=$rows['marks']; //should get value 55 and so on
}
If your values are comma separated then explode the field.
http://php.net/manual/en/function.explode.php
include("db_connect.php");
$result = mysql_query("SELECT * FROM students", $con);
while($rows = mysql_fetch_array($result)) {
$mark=explode(',', $rows['marks']);//what will do here
foreach($mark as $out) {
echo $out;
}
}
Explode the data from the database. Use the explode function.
Access using indexes
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
$mark1 = $exp[0]; //result is 50
$mark2 = $exp[1]; //result is 55
$mark3 = $exp[3]; //result is 67
}
Or loop using foreach
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
foreach($exp as $mark) {
echo $mark;
}
}
If that row contains ,, the just use explode():
while($rows = mysql_fetch_assoc($result)) {
$mark1 = explode(',', $rows['marks']); // should contain the comma separated values
// in array form
// then loop again
foreach($mark1 as $mark_piece) {
// do something here
}
}
You should use the explode function
$marks = explode(",", $rows['marks']);
foreach($marks as $mark){
//your code to do something with the mark.
}
N.B. explode() function breaks the string into array, it accepts three arguments, first one is the delimiter that specifies where to break the string, second one is the string that needs splitting, and third one is not mandatory but it tells how many array to return.
$str_to_exploade = 'This,string,needs,some,exploiting';
$explode_string = explode(',', $str_to_exploade);
echo '<pre>';
print_r($explode_string);
echo $explode_string[0].'<br/>';
echo $explode_string[1];
More about explode() go to : http://php.net/manual/en/function.explode.php
I have text :
$a = I wanna eat apple , and banana .
I wanna get every words and punctuation of that sentence :
$b = explode(' ', strtolower(trim($a)));
the result of explode is array.
I have a words table on db that has fields : id, word and typewords all in lowercase. but for punctuation there are no exist in db.
I wanna search every words in db to take the type of words, so the final result that i want to get is :
words/typeofwords = I/n wanna/v eat/v apple/n ,/, and/p banana/n ./.
here's the code :
function getWord ($word){
$i = 0 ;
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
while ($row = mysql_fetch_array($query)) {
$word[$i] = $row['typewords'];
$i++;
}
return $word;
}
echo $b.'/'.getWord($b);
but it doesn't work, please help me, thanks !
Try with this:
function getWord($words){
$association = array();
foreach($words as $word)
{
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
if($row = mysql_fetch_array($query))
$association[$word] = $row['typewords'];
elseif(preg_match('/[\.\,\:\;\?\!]/',$word)==1)
$association[$word] = $word;
}
return $association;
}
$typewords = getWord($b);
foreach($b as $w)
echo $w.'/'.$typewords[$w];
function getWord($word){
// concat the word your searching for with the result
// http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
$query = mysql_query("SELECT CONCAT(word,'/',typewords) as this_result FROM words WHERE word = '$word' ");
$row = mysql_fetch_array($query);
return $row['this_result']." "; // added a space at the end.
}
// loop through the $b array and send each to the function
foreach($b as $searchword) {
echo getWord($searchword);
}
You assume the function parameter to be an array, but it is a string.
Edit: In your function you treat $word as an array as well as a string. Decide what you want and recode your function.
I am printing a set of words that is placed in a MySQL database and I am retrieving it with PHP. I want to present it as a comma separated list, but I need it not to print or remove the last comma. How could I do this?
I did try to use rtrim, but I did not probably do it right.
This is my code as it is today:
<?php
$query0 = "SELECT LCASE(ord) FROM `keywords` ORDER BY RAND()";
$result0 = mysql_query($query0);
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keyword = $row0['LCASE(ord)'];
echo "$keyword, ";
?>
I did try to use rtrim, my attempt was something like this (I might be honest enough to say that I am in above my head in this ;) )
$keyword = $row0['LCASE(ord)'];
$keywordc = "$keyword, ";
$keyword- = rtrim($keywordc, ', ');
echo "$keyword-, ";
As you might imagine, this did not print much (but at least it did not leave me with a blank page...)
I would do:
$keywords = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keywords[] = $row0['LCASE(ord)'];
}
echo implode(',', $keywords);
I usually do this by placing the results in an array first
$some_array = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) {
$some_array[] = $row0['LCASE(ord)'];
}
then simply:
echo "My List: " . implode(', ', $some_array);
// Output looks something like:
My List: ord1, ord2, ord3, ord4
substr($string, 0, -1);
That removes the last character.
I have the following which produces results for me.
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
echo $author['fullname'] .', ';
}
It prints it out perfect, except on the last run it still adds the comma and space, is there a way i can strip this from the last result, so its:
name, name, name, name
Instead of the following
name, name, name, name,
Cheers
A better way of doing this would be to separate out the handling of database results from the view/output logic, and then you can sidestep the issue all together, using implode to allow PHP to join each of your authors together into a single string, split by your delimiter of a comma and a space:
// your loop {
$authors[] = $author['fullname'];
}
// your output
echo implode(', ', $authors);
Just concate the data into a string and then remove the last 2 chars using
$author['fullname'] = substr($author['fullname'], 0, -2);
Refer the manual for substr http://php.net/manual/en/function.substr.php
Instead of echoing each author out you could put them in a string and then simply use trim() to take off the trailing comma and finally echo the whole string.
this will probably work
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
//echo $author['fullname'] .', ';
}
$name_count = count($author[]);
for($x=0;$x<$name_count ;$x++){
if($x == $name_count -1){
echo $author['fullname'];
}else{
echo $author['fullname'].", ";
}
}
the idea is to detect the last array index, so that we can apply all the commas after each name except to the last one.
don't ever echo inside foreach
$var = '';
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
$var .= $author['fullname'] .', ';
}
echo trim($var,', ');