PHP display comma separated GROUP_CONCAT values separately - php

This question is with reference to my previous question posted here PHP display results equivalent to comma separated values in the database.
I nearly solved the problem. Now I am stuck somewhere else which if solved my issue will be solved.
The problem is:
Please have a look at this code first
<div class="ads-container">
<?php
$cat = $pdo->prepare("SELECT * FROM ads_category");
$cat-> execute();
$i = 0;
while($s = $cat->fetch()){
$ads = $pdo->prepare("SELECT *, GROUP_CONCAT(memberships.mbs_color) FROM advertisements
INNER JOIN memberships ON FIND_IN_SET(memberships.mbs_id, advertisements.ad_memberships)
LEFT JOIN ads_category ON advertisements.ad_category = ads_category.ac_id
WHERE ad_credits >= ac_credits AND ad_category = :cat AND ad_status = 'active'
GROUP BY advertisements.ad_id");
$ads-> bindValue(':cat', $s['ac_id']);
$ads-> execute();
while($a = $ads->fetch()){ extract($a);
?>
<div class="" <?php if($i++ != 0){ echo "style='margin-top: 30px'"; } ?>>
<i class="fa fa-bullhorn" aria-hidden="true"></i> <?php echo $ac_category; ?>
</div>
<div class="col-sm-4">
<div class="adcover">
<div class="ad-title">
<?php echo $ad_title; ?>
</div>
<div class="ad-footer-two"> <?php echo $a['GROUP_CONCAT(memberships.mbs_color)']; // this is giving me the values comma separated perfectly ?>
<span class="membership-indicator" style="background: <?php echo $mbs_color; ?>; margin-top: 4px; margin-left: 5px"></span>
</div>
</div>
</div>
<?php } } ?>
</div>
Now the problem is when I echo <?php echo $a['GROUP_CONCAT(memberships.mbs_color)']; ?> I get the comma separed color values perfectly. But I want to display it as a color not as a word in <span class="membership-incdicator"></span> as exactly as in https://prnt.sc/hvj91s. So, how can I do that? Do I have to use foreach() function here? If yes then please tell me how to write that code. If not, then please tell me how to accomplish this.

This whole thing looks very messy, but explode the list and loop:
$mbs_colors = explode(',', $a['GROUP_CONCAT(memberships.mbs_color)']);
foreach($mbs_colors as $color) {
echo '<span class="membership-indicator" style="background: ' . $color . '; margin-top: 4px; margin-left: 5px"></span>';
}
Also, you can use an alias: SELECT *, GROUP_CONCAT(memberships.mbs_color) AS colors and then use: $a['colors'].
This does beg the question; why GROUP_CONCAT then? I'm not sure but there must be a better query.

Related

while - fetch array | how to get the code of each output?

I am making a system and I need to see information for each student. When I click the button, I need to know the student's code and open a page (seeStudent.php) with the student's information. Can someone help me?
<?php
$sql = $conn->query("SELECT * from tb_coordinator inner join tb_teacher
on tb_coordinator.cd_coord = tb_teacher.cd_coord
inner join teacher_class on
tb_teacher.cd_teacher = teacher_class.cd_teacher
inner join tb_teacher on
teacher_class.cd_class = tb_class.cd_class
inner join tb_student on
tb_class.cd_class = tb_student.cd_class
where tb_teacher.cd_cpf = '$cpf' and nm_class = '3a1' order by cd_number asc");
while($row = mysqli_fetch_array($sql)){
$nm_student = $row['nm_student'];
$cd_number = $row['cd_number'];
?>
<ul class="list-group list-group-flush" style="width: 50%; margin-top: 2%;">
<div id="load_student">
<li class="list-group-item"><?php echo $cd_number . " - " . $nm_student;?>
Get Information</button></li>
</div>
</ul>
</div>
<?php }?>
You need a bit modification in your prepared HTML. Add your required parameters to the anchor href which might help you to get student details from database in seeStudent.php page.
<ul class="list-group list-group-flush" style="width: 50%; margin-top: 2%;">
<div id="load_student">
<li class="list-group-item"><?php echo $cd_number . " - " . $nm_student;?>
<a href="seeStudent.php?cd_number=<?=$cd_number?>&nm_student=<?=$nm_student?>" >
<button type="button" class="btn btn-outline-info" style="margin-left: 90%;">Get Information</button>
</a>
</li>
</div>
</ul>
If you click Get Information button, it will be taken you to seeStudent.php with two $_GET parameters (cd_number, nm_student).
Now the final task. In seeStudent.php page take the parameter from $_GET array and do other query to get student details from database and to display.
seeStudent.php
<?php
$cd_number = isset($_GET['cd_number']) ? $_GET['cd_number'] : '';
$nm_student= isset($_GET['nm_student']) ? $_GET['nm_student'] : '';
// .... code stuff, possibly query and display
?>

PHP while loop is returning only one value

I know that are several questions similar to this one, and i have looked at them, but still i haven't managed to modify my function in order to work.
So i have this function getCar_2(); in functions.php page. The thing is that it should display more cars, because i have more cars in the database, but it displays only the last one. Same with getCar_1(), the two functions are the same.
Here is the function:
<?php
function getCar_2(){
global $connect;
$text = "";
$get_car_2 = "SELECT * FROM cars WHERE category_id=5";
$get_car_result_2 = mysqli_query($connect, $get_car_2) or die(mysqli_query());
while($row_car_2 = mysqli_fetch_array($get_car_result_2)){
$car_model_2 = $row_car_2['car_name'];
$car_image_2 = $row_car_2['car_image'];
if(isset($car_model_2) && isset($car_image_2)){
$text = "
<div id='' style='white-space:nowrap;'>
<p id='model' style='display:inline-block; margin-right:10px; margin-left:10px; padding-top:10px; position:relative; bottom:35px;'>$car_model_2</p></a>
<img src='administrator/images/$car_image_2' width='120' height='80' style='display: inline-block; box-shadow: 0 0 11px #000;'/><br>
</div>";
}
}
return $text;
}
?>
and is displayed on another page like this:
<?php
$car_1 = getCar_1();
$car_2 = getCar_2();
if(!empty($car_1) || !empty($car_2)){
?>
<div class="block">
<div class="up">
<div class="title"><h4>Cars</h4></div>
</div>
<div class="down">
<div class="column_1"><b><?php echo $car_1; ?></b></div>
<div class="column_2"><b><?php echo $car_2; ?></b></div>
</div>
</div>
<?php
}
?>
You are not concatenating your text variable, so on each loop pass it will contain only the last value. You should use concatenation operator .= instead of assignment operator =
$text .= "
You are overwriting the previous row values before they are used. Looks like you want to append new row results to the prior one, for that.. just need to add one line and one period...
$text =''; //define $text so you can append to it
if(isset($car_model_2) && isset($car_image_2)){
$text .= "
<div id='' style='white-space:nowrap;'>
......
Notice the .= to append the new result to the previous row.
Appending variables this way is called concatenation.
Periods are also used to concatenate strings and variables for printing.
Like . . .
echo '<div class="column_1"><b>'. $car_1.'</b></div>';

Last row still shows <div>

I'm learning PHP/MySQLi at the minute and I need help with something I just can't seem to find online. I am using <div class="hr"> </div> after every topic in the forum script I am making but I don't want it to display one after the last topic their is, how do I stop my script from displaying it after the last row? I would be grateful for any help and just so I'm a 100% clear.
Here is how it looks:
Topic Title Here
-------------------------------------
Topic Title Here
-------------------------------------
But I want:
Topic Title Here
-------------------------------------
Topic Title Here
My code of where this part is:
<?php
}
$dn2 = mysql_query('select t.id, t.title, t.authorid, u.username
as author,
count(r.id) as replies from topics as t left join topics as r on
r.parent="'.$id.'"
and r.id=t.id and r.id2!=1 left join users as u on u.id=t.authorid
where t.parent="'.$id.'" and t.id2=1 group by t.id order by t.timestamp2 desc');
if(mysql_num_rows($dn2)>0)
{
?>
<table id="main-table">
<tr>
<td id="side">
</td>
<td id="content">
<?php
while($dnn2 = mysql_fetch_array($dn2))
{
?>
<div><a href="read_topic.php?id=<?php echo $dnn2['id']; ?>">
<?php echo htmlentities($dnn2['title'], ENT_QUOTES, 'UTF-8'); ?></a>
- <a class="wtb" href="profile.php?id=<?php echo $dnn2['authorid']; ?>">
<?php echo htmlentities($dnn2['author'], ENT_QUOTES, 'UTF-8'); ?></a></div>
<div class="hr"> </div>
<?php
}
?>
Without seeing your code, an easy way to fix it would be to draw the line first unless it's the first topic
if ($topicNumber != 1) echo ('<div class="hr"> </div>');
<div><?php echo $dnn1['topic']; ?><div>
<? } ?>
You can handle this easily with your css:
<style>
.wrapper div {border-bottom: 1px dashed black}
.wrapper div:last-child{ border-bottom: 0}
</style>
<div class="wrapper">
<div><?php echo $dnn1['topic']; ?><div>
<? } ?>
</div>

PHP Function and array Syntax Issue

I'm really struggling with something and wondered if anyone could spare a few moments to have a look at this code block.
The original line looked like this:
$home_collectionsx=get_home_page_promoted_collections();
This brought back all the promoted to homepage items and displayed them on the homepage. I however simply want to pull 1 item in using the same code and an array function, the id is 5 for this purpose so I thought adding =array(5) or (array (5)) would work - but it doesn't.
I'm hoping it's something simple, or something that I have missed or not written correctly.
<?php
if(!hook("EditorsPick")):
/* ------------ Collections promoted to the home page ------------------- */
$home_collectionsx=get_home_page_promoted_collections (array(5));
foreach ($home_collectionsx as $home_collectionx)
{
?>
<div class="EditorsPick">
<div class="HomePanel"><div class="HomePanelINtopEditors">
<div class="HomePanelINtopHeader">Editors Pick</div>
<div class="HomePanelINtopText">This is the editors pick of Asset Space...</div>
<div class="EditorsPicImage"><div style="padding-top:<?php echo floor((155-$home_collectionx["thumb_height"])/2) ?>px; margin-top: -24px; margin-bottom: -15px;">
<a href="<?php echo $baseurl_short?>pages/search.php?search=!collection<?php echo $home_collectionx["ref"] ?>" onClick="return CentralSpaceLoad(this,true);"><img class="ImageBorder" src="<?php echo get_resource_path($home_collectionx["home_page_image"],false,"thm",false) ?>" width="<?php echo $home_collectionx["thumb_width"] ?>" height="<?php echo $home_collectionx["thumb_height"] ?>" /></div>
</div></div>
</div>
</div>
</div>
<?php
}
endif; # end hook homefeaturedcol
?>
This is the function to the DB itself that the above code is connecting to…
function get_home_page_promoted_collections()
{
return sql_query("select collection.ref,collection.home_page_publish,collection.home_page_text,collection.home_page_image,resource.thumb_height,resource.thumb_width from collection left outer join resource on collection.home_page_image=resource.ref where collection.public=1 and collection.home_page_publish=1 order by collection.ref desc");
}
Any help would be hugely appreciated :-)
Many many thanks
Rich
That function doesn't take a parameter: get_home_page_promoted_collections()
You want something like:
$home_collectionsx=get_home_page_promoted_collections(5);
And:
function get_home_page_promoted_collections($id=null)
{
$filterClause = '';
if(!is_null($id))
{
//to only return this id
$filterClause = ' AND collection.ref = '.intval($id);
//to get all but that id
$filterClause = ' AND collection.ref != '.intval($id);
}
return sql_query("SELECT collection.ref,collection.home_page_publish,collection.home_page_text,collection.home_page_image,resource.thumb_height,resource.thumb_width FROM collection LEFT OUTER JOIN resource on collection.home_page_image=resource.ref WHERE collection.public=1 AND collection.home_page_publish=1".$filterClause." ORDER BY collection.ref DESC");
}

Displaying PHP Functions With HTML/CSS

I have some php and css code that I'm trying to break down into functions. I need some advice on how to approach this.
<?php
$info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));
while ($info_row = mysqli_fetch_array($info))
{
$info_id = $info_row['info_id'];
$info_title = $info_row['info_title'];
?>
<div style="width: 100%;">
<div style="float: left;">
<?php echo $info_id; ?>
</div>
<div style="float: left;">
<?php echo $info_title; ?>
</div>
<div style="clear: both;"></div>
</div>
<?php } ?>
This appears as such:
1 One
2 Two
3 Three
4 Four
Below is what I have so far with separating everything into functions:
function get_info()
{
$dbc = get_dbc();
$info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));
while ($info_row = mysqli_fetch_array($info))
{
$result[] = $info_row;
}
mysqli_free_result($info);
return $result;
}
function display_info_id()
{
$result=forum();
foreach ($result as $info_row)
{
$info_id = $info_row['info_id'];
echo $info_id;
}
}
function display_info_title()
{
$result=forum();
foreach ($result as $info_row)
{
$info_title = $info_row['info_title'];
echo $info_title;
}
}
<?php get_info(); ?>
<div style="width: 100%;">
<div style="float: left;">
<?php display_info_id(); ?>
</div>
<div style="float: left;">
<?php display_info_title(); ?>
</div>
<div style="clear: both;"></div>
</div>
This displays as:
1234 OneTwoThreeFour
I understand why it displays as such, but I don't understand how to get it to show the way I want it to. Any advice would be helpful.
Edit--
Is this at all possible to do with the 3 functions I have? I do not want info_id and info_title in the same function.
When I look at software, such as WordPress, it seems I may have to surround my HTML in some kind of loop, and change the way the functions get info?
You are calling a separate loop for each of your variables. It is kind of unnecessary to split this into multiple functions, since the loop requires that the two variables be displayed together.
How would I handle it? I would store the SQL result into a complete array, then loop over that array to output your HTML. That could be split into two functions, if you wish. Maybe useful if you need to use the results more than once on the page.
I'm using the HEREDOC string syntax to combine the PHP variables, (wrapped in {}) with the HTML block. This saves you having to jump in and out of PHP via <?php ?>
// This function is fine.
function get_info()
{
$dbc = get_dbc();
$info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));
while ($info_row = mysqli_fetch_array($info))
{
$result[] = $info_row;
}
mysqli_free_result($info);
return $result;
}
function display_result($result)
{
// Loop over your results and display each
foreach ($result as $r)
{
// Now use the HEREDOC syntax to form your HTML block instead
// of intermingling PHP function calls
echo <<<HTML
<div style="width: 100%;">
<div style="float: left;">
{$r['info_id']}
</div>
<div style="float: left;">
{$r['info_title']}
</div>
<div style="clear: both;"></div>
</div>
HTML;
// There must be no whitespace before or after the HTML; on the previous line!
}
}
Now to retrieve your data and display it:
<?php
$results = get_info();
display_result($results);
?>
You need to refactor your display logic into one loop, instead of two separate loops.
For example:
<?php get_info(); ?>
<div style="width: 100%;">
<div style="float: left;">
<?php display_info_id(); ?>
</div>
<div style="float: left;">
<?php
$result=forum();
foreach ($result as $info_row)
{
$info_id = $info_row['info_id'];
$info_title = $info_row['info_title'];
echo $info_id . " . $info_title . "<br/>\n";
}
?>
</div>
<div style="clear: both;"></div>
</div>

Categories