Echoing out a variable variables list - php

I need to create a string like ‘Acme’, ‘Umbrella’, ‘Waymart’ for use in a java function. So far, I have:
$info0 = "SELECT DISTINCT Company FROM CETracker";
$rs0=odbc_exec($conn1,$info0);
$count = 1;
while($row = odbc_fetch_array($rs0))
{
${'V'.$count++} = "" . $row['Company'] . "";
}
$categories = "'$V1', '$V2', '$V3'";
echo $categories;
I then have $categories echo in the place the function needs the company list. This work as long as there are just 3 companies. But when more are added, I’ll have to add ‘$V4’, ‘$V5’ and so on. Any ideas? Thanks.

Use arrays instead of variable variables, you can then implode the results:
$info0 = "SELECT DISTINCT Company FROM CETracker";
$rs0 = odbc_exec($conn1,$info0);
$companies = array();
while($row = odbc_fetch_array($rs0)) {
$companies[] = "'" . $row['Company'] . "'";
}
$categories = implode(', ', $companies);
echo $categories;
... if you would like to continue with variable variables, use a loop to create your string:
$info0 = "SELECT DISTINCT Company FROM CETracker";
$rs0=odbc_exec($conn1,$info0);
$count = 1;
while($row = odbc_fetch_array($rs0)) {
${'V'.$count++} = "" . $row['Company'] . "";
}
$categories = '';
for($x = 1; $x <= $count; $x++) {
if($x > 1) $categories .= ', '; // add the comma
$categories .= "'" . ${'V'.$x} . "'"; // add the variable variable
}
echo $categories;

Please try this:
$info0 = "SELECT DISTINCT Company FROM CETracker";
$rs0=odbc_exec($conn1,$info0);
$count = 1;
$str = '';
while($row = odbc_fetch_array($rs0))
{
$str .= "'".$row['Company']."',";
}
$str = substr($str,0,strlen($str)-1);
echo $str;

Related

PHP loop outputting duplicates

public function select(){
$rows = [];
$connection = $this->connect();
$result = $connection->query("SELECT username FROM users");
while ($row = $result->fetch_assoc()){
$rows[] = $row;
}
$userlist = 0;
foreach($rows as $username){
$userlist .= $username['username'];
}
$get_rankings = [1,2,3,4];
$get_image_path = "images/";
$total = 0;
for ($x = 0; $x < count($get_rankings); $x++){
$total = $get_rankings[$x];
$path .= "<img src = '" . $get_image_path . $total . ".png'>\n" . $userlist . "<br/>";
// echo "<span class = 'align-down'>{$path}";
// echo "<p class = 'user-name'> {$rows['0']}</p>";
// echo "</span>";
}
echo $path;
}
I'm trying to output a simple ranking but using the number index as images to display them.
In the past i've tried to do something similar but couldn't figure out how to match player it with images on the side.
The output im getting is this:
It's outputting each entry 4 times(I get why, its in a loop) but I can't figure out the correct solution to write it outside of a loop or properly
The desired output is:
My DataBase reads as:
[id][username][password]
If there is an easier solution, i'm all ears. I don't know how to approach this.
There's no need for $userlist. Output the username from $rows[$x].
$path = "";
$max = min(count($rows), count($get_rankings));
for ($x = 0; $x < $max; $x++){
$total = $get_rankings[$x];
$path .= "<img src = '" . $get_image_path . $total . ".png'>\n" . $rows[$x]['username'] . "<br/>";
// echo "<span class = 'align-down'>{$path}";
// echo "<p class = 'user-name'> {$rows['0']}</p>";
// echo "</span>";
}

Returning JSON from a PHP function

I want to transform this PHP function.. that should return JSON data.
<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order']))
if (isset($_GET['cat'])) {
$query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
. "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";
$random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
. $wpdb->escape($_GET['cat']) . "'");
if (!$random)
$order = $wpdb->get_var(NULL, 1);
}
if (isset($_GET['order']))
$order = $_GET['order'];
if ($order != '') {
if (isset($_GET['cat']))
$query .= ' AND ';
else
$query .= ' WHERE ';
$tracks = mix_player::order_list($query, $order);
}
} else {
$random = '0';
}
$query .= ' ORDER BY `id` ASC';
if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
// option "shuffle = true" not always working into mix. Do it our own way...
if ($random == 1) { // shuffle tracks?
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$nrows = count($tracks);
for ($i = 0; $i < $nrows; $i++) {
$j = mt_rand(0, $nrows - 1); // pick j at random
$row = $tracks[$i]; // swap i, j
$tracks[$i] = $tracks[$j];
$tracks[$j] = $row;
}
}
foreach ($tracks as $row) {
$artist = (mix_player::entities($row['artist']));
echo ($artist);
$title = (mix_player::entities($row['title']));
echo ($title);
$url =(xspf_player::entities($row['url']));
echo ($url);
}
}
?>
to display like this json file :
{"title":"title", "artist":"artist","media":"url media.mp3","color":"#56B0E8" },
Can you help me?
Thanks in advance.
You can simply create an array and populate it with your desired values, then return it as JSON:
function tracks2json( $tracks )
{
$retval = array();
foreach( $tracks as $row )
{
$array = array();
$array['artist'] = mix_player::entities($row['artist']);
$array['title'] = mix_player::entities($row['title']);
$array['media'] = 'url '.xspf_player::entities($row['url']);
$array['color'] = '#56B0E8';
$retval[] = $array;
}
return json_encode( $retval );
}
if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
// Your MySQL routine here
$json = tracks2json( $tracks );
}
echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));

Why does the loop execute only once?

I have the following small code which manipulate tweets data. I expect my loop to iterate 10 times. However, what happens is that it iterates only once and then exits, with no sign of any error relating to MySQL or otherwise.
$query = "select data from tweets where `screen_name` = 'username' limit 10";
$tweetsq = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
$tweets = mysqli_fetch_assoc($tweetsq);
$tweets_count = mysqli_num_rows($tweetsq);
echo $tweets_count . '<br />'; //See output
$count = 0;
foreach ($tweets as $raw_tweet) {
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
$is_reply = (isset($tweet->in_reply_to_screen_name) && strlen($tweet->in_reply_to_screen_name) > 0) ? 1 : 0;
$is_retweet = (isset($tweet->retweeted_status) && $tweet->retweeted_status != '') ? 1 : 0;
$entity_holder = array();
$has_hashtag = $has_url = $has_mention = $has_media = 0;
foreach ($tweet->entities as $type => $entity) {
if (is_array($entity) && count($entity) < 1) {
//continue;
} else {
$entity = array_pop($entity);
switch ($type) {
case 'hashtags' : $has_hashtag = 1; break;
case 'urls' : $has_url = 1; break;
case 'user_mentions' : $has_mention = 1; break;
case 'media' : $has_media = 1; break;
default :
}
}
}
echo 'Updating recorde... <br />';
$query = "UPDATE tweets SET is_reply='" . $is_reply . "' , is_retweet='" . $is_retweet . "', has_hashtag='" . $has_hashtag . "', has_url='" . $has_url . "', has_mention='" . $has_mention . "', has_media='" . $has_media . "' WHERE tweet_id='" . $tweet_id . "'";
$result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
var_dump($result); //See output
$count++;
echo '<br />';
}
echo $count;
Output:
10 //This is the value of $tweets_count
Updating recorde...
bool(true) //The result of the UPDATE query
1 //The value of $count at the end of script. It SHOULD be 10
mysqli_fetch_assoc fetches a single row as an associative array where the key is the column name and the value is the column value. The correct way to use it would be to iterate over the result set until the fetch returns NULL, indicating that there are no more rows to fetch:
while ($row = mysqli_fetch_assoc($tweetsq)) {
$raw_tweet = $row["data"];
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
# etc...

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

IF ISSET not working?

IN DB
row1 (type column=apple), (stage column=1)
row2 (type column=orange), (stage column=NULL)
IN PHP
$query = mysql_query("SELECT * from fruits");
$row = mysql_fetch_array($query);
$num = mysql_num_rows($query);
$i=0;
$storeMyData = array();
while($row = mysql_fetch_array($query))
{
if(isset($row['type'])){
$type = "-" . $row['type'];
} else {
$type = NULL;
}
if(isset($row['stage'])){
$stage = "STAGE " . $row['stage'];
} else {
$stage = NULL;
}
$fruit = implode (", ", array_filter(array($type, $stage)));
// This will show 2 rows of data
$storeMyData[] = $fruit;
// store current data in array
$i++;
}
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
/* or join the data using string concatenation */
$allFinalData2 = "";
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
$allFinalData2 = $allFinalData2.$prevData ; // keep on concatenating
}
echo $allFinalData2;
The final output shows as "Apple, Stage 1" "Orange, Stage".
How can I show it "Apple, Stage 1" "Orange" without the word Stage if stage is NULL for
row2 (orange) in DB.
Change this line
while($i < $num)
to this
while($row = mysql_fetch_array($query))
also, there is no need to call mysql_query inside your loop, use this to prevent confusion.
$type = "-" . $row['type'];
$stage = "STAGE " . $row['stage'];

Categories