Output as array - php

$result = mysql_query(" SELECT p.page_url AS url,
COUNT(*) AS occurrences
FROM page p, word w, occurrence o
WHERE p.page_id = o.page_id AND
w.word_id = o.word_id AND
w.word_word = \"$keyword\"
GROUP BY p.page_id
ORDER BY occurrences DESC
" );
$output = "<loginsuccess>";
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
}
$output .= "</loginsuccess>";
print ($output);
I am gettign the output in XML, instead i want it in array... how to achieve this.
The code below is not working...
$ret = array();
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$tmp['url'] = $row['url'];
$tmp['occurrences'] = $row['occurrences'];
$ret[] = $tmp;
}
return $ret;

You're already getting the results in an array when you call mysql_fetch_array($result). That's what mysql_fetch_array does.
Unless you want some other kind of array format? If so, you'll have to be more specific.

Use print_r():
echo "<pre>";
print_r($row);
echo "</pre>";
Note: If you won't wrap it in <pre> tags, the output will be difficult to read as it will appear all on one line

A for-loop is only to be used in an incremental fashion, you attempted to use it in place of a while loop. This isn't "do 1,000 times" but "do while we have a row to use".
Try this:
while($row = mysql_fetch_array($result)) {
$tmp['url'] = $row['url'];
$tmp['occurrences'] = $row['occurrences'];
$ret[] = $tmp;
}
return $ret;

Try it like so, notice the here-doc style of writing the SQL statement. I find it very helpful. Also I would suggest rewriting the SQL to use JOINs instead of crowding the WHERE clause with join criteria.
$sql = <<<EOSQL
SELECT p.page_url AS url, COUNT(*) AS occurrences
FROM page p, word w, occurrence o
WHERE p.page_id = o.page_id AND
w.word_id = o.word_id AND
w.word_word = "$keyword"
GROUP BY p.page_id
ORDER BY occurrences DESC;
EOSQL;
$result = mysql_query($sql) or die('failed to execute the query');
while ($row = mysql_fetch_array($result)) {
print_r ($row);
}
Hope this is roughly what you're after

You need to initialize your $tmp array before using it.

Related

Remove last comma from string in while loop

My select query is like this, in group_name i am giving comma but I want to remove comma from last. I already tried with trim but it removes all commas, and I want to remove last comma only.
$selctGroup = "SELECT contact_id,group_name FROM contact_group
LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id`
WHERE contact_id = ".$row['contact_id'];
$selctGroupRes = mysql_query($selctGroup);
while($groupRow = mysql_fetch_array($selctGroupRes))
{
echo $groupRow['group_name'].',';
}
Instead of echoing out each line, build up a string to echo at the end. Before that, remove the lingering comma from the end with rtrim($str,",").
$str = "";
while($groupRow = mysql_fetch_array($selctGroupRes)) {
$str .= $groupRow['group_name'].',';
}
echo rtrim($str,",");
$selctGroup = "SELECT contact_id,group_name FROM contact_group
LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id`
WHERE contact_id = ".$row['contact_id'];
$selctGroupRes = mysql_query($selctGroup);
$str='';
while($groupRow = mysql_fetch_array($selctGroupRes))
{
if($str=='')
$str=$groupRow['group_name'];
else
$str.=','.$groupRow['group_name'];
}
echo $str;
Using rtrim().Like below
rtrim($groupRow['group_name'])
Store your data in array and using implode you can remove last comma
while($groupRow = mysql_fetch_array($selctGroupRes))
{
$result[] = $groupRow['group_name'];
}
echo implode(",", $result);

Get value from SQL database

I am trying to get a series of 'titles' from a database, and place them in an array as individual strings for each title. Currently I am using this code
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$totalRows_getLatest = mysql_num_rows($getLatest);
$latestNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
}
and when I call them individually using
echo $latestNews[0][0];
I get the string value.
However, I would like to place these strings in to a single array, thereby generating an array of strings. I have tried this:
$latestNews = array();
$extractNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
$extractNews[] = $latestNews[i][0];
}
but it doesn't return the string in the output extractNews array.
What am I doing wrong?
Thanks
Is this what you are looking for?
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$latestNews = array();
while($row = mysql_fetch_assoc($getLatest)) {
$latestNews[] = $row['title'];
}
echo "<pre>" . print_r($latestNews,1) . "</pre>";
WATCH OUT
Please do not use the mysql_* functions anymore. They are deprecated and won't be supported in >= php 5.5. Switch to mysqli_* or PDO.

PHP how to remove last separator?

I have tried a tons of variations, but I can't find the solution. Previously the output was like this:
word a
word b
word c
etc
I have changed some parts of code and now output is:
word a | word b | word c |
How to remove last separator?
The code is:
<div id="right">
<div id="synonyms">
<?
$separator = '<span class="pipe">|</span>';
$sql = mysql_query("SELECT DISTINCT word, id_word FROM words WHERE word LIKE '$word' ORDER BY word ASC LIMIT 100");
echo mysql_error();
while ($row=mysql_fetch_row($sql))
{
$word_synonym = $row[0];
$id_word_synonym = $row[1];
$sql2 = mysql_query("SELECT DISTINCT synonym, id_synonym FROM synonyms WHERE id_word = '$id_word_synonym' ORDER BY synonym ASC");
echo mysql_error();
$num_results =mysql_num_rows($sql2);
while ($row=mysql_fetch_row($sql2))
{
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
echo "".$separator."".$synonym." ";
}
}
?>
</div>
I tried to add $separator = substr($separator, -1, 0); and a lot of other suggestions, but without result.
My preference when doing something like this is to build an array of the strings, then use implode when outputting the final string. This is particularly useful because then I can do other things like merge groups, filter them, etc.
This was posted before and removed, but I think it's worth including as an optional method. Although I prefer Kolink's method, I've used this, too:
Use an iterator ($i) to identify the first (or last) item.
$i=0;
while ($row = mysql_fetch_row($sql2)) {
$i++;
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
echo ($i>1?$separator:"").'$synonym';
}
Not part of this answer, but here's an example of Kolink's (arguably superior) method:
$links=array();
while ($row = mysql_fetch_row($sql2)) {
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
$links[]='$synonym';
}
if (!empty($links)) {
echo implode($separator,$links);
}

Remove last comma or prevent it from being printed at all MySQL/PHP

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.

How to Remove PHP Array Implode Character from Beginning of String

I am working on a project that requires imploding an array with character separation. I have successfully used join and implode interchangeably in other parts of the project, but I can't get it to work in this section.
$dbQuery = "SELECT ftc.*, fc.name
FROM facilities f
LEFT JOIN facility_to_category ftc ON f.fid = ftc.fid
LEFT JOIN facility_categories fc ON ftc.cid = fc.cid
WHERE f.listing_year = '2011'
AND fc.parent_cid = '2'
AND f.fid = ('".$listing_fid."')";
$dbResult = $dbc->query($dbQuery,__FILE__,__LINE__);
$num_results = $dbc->num_rows($dbResult);
echo '<h3>Demographics</h3>
<div>';
while($catdata = $dbc->fetch($dbResult)) {
$demographics = array();
$demographic_names = array('',trim($catdata->name));
$demographics = implode(' '.chr(149).' ',$demographic_names);
print $demographics;
}
The result is this:
Demographics
• Affluent • Children • Hard-to-Reach • Parents
instead of
Demographics
Affluent • Children • Hard-to-Reach • Parents
I've tried using double quotes instead of single quotes around '.chr(149).'. I've tried using commas or bars or just spaces. I've tried different ways of trimming and not trimming $catdata->name.
I also thought about trying string concatenation, but then I'll end up with an extra character at the end instead of the beginning. Implode or join seem the better way to go.
What am I missing?
I am not sure I understand what you are trying to do, but why not use
$demographics_names = array();
while($catdata = $dbc->fetch($dbResult)) {
array_push($demographics_names, trim($catdata->name));
}
$demographics = implode(' '.chr(149).' ',$demographic_names);
print $demographics;
Thank you, everyone, for your help! I ended up reformatting the query and array. Here is the final code:
$dbQuery = "SELECT ftc.*, fc.name
FROM facilities f
LEFT JOIN facility_to_category ftc ON f.fid = ftc.fid
LEFT JOIN facility_categories fc ON ftc.cid = fc.cid
WHERE f.listing_year = '2011'
AND fc.parent_cid = '2'
AND f.fid = ('".$listing_fid."')";
$dbResult = $dbc->query($dbQuery,__FILE__,__LINE__);
$num_results = $dbc->num_rows($dbResult);
echo '<h3>Demographics</h3>
<div>';
while($catdata = $dbc->fetch($dbResult)) {
$demographics = array();
if (is_array($demographics)) {
$demographic_names[] = trim($catdata->name);
}
}
$demographics = join(' '.chr(149).' ',$demographic_names);
print $demographics;
The result is:
Demographics
Affluent • Children • Hard-to-Reach • Parents
Hopefully this will be helpful to someone else!
You're inserting a blank element into the array that you're imploding:
$demographic_names = array('',trim($catdata->name));
^--- here
Seems like you have a blank demographic_name. Use array_filter on the resulting array.
Check the first array is empty.
while($catdata = $dbc->fetch($dbResult)) {
$demographics = array();
$demographic_names = array('',trim($catdata->name));
if(!empty($demographic_names))
{
$demographics = implode(' '.chr(149).' ',$demographic_names);
print $demographics;
}
}

Categories