Fetch comma seperated link list from MySQL - PHP - php

id name
1 Abc
2 Bcd
3 Def
4 Efg
5 Xyz
Now i am using mysqli prepared statements to fetch my data
<?php
if ($stmt1 = $mysqli->prepare("SELECT name FROM TABLE")) {
$stmt1->execute();
$res1 = $stmt1->get_result();
while($rwv=mysqli_fetch_array($res1)) {
?>
<?php echo $rwv['name']; ?>
<?php } } $stmt1->close(); ?>
Output i get on using above query:
AbcBcddefEfgXyz
Desired Ouput:
Abc, Bcd, Def, Efg, Xyz
I searched on Google and found solutions to use GROUP_CONCAT func. I used GROUP_CONCAT function but then it shows an error on a href that variable "name" is undefined. How i can get the desired output ?? Thanks in advance...

Please check below example, You can use GROUP_CONCAT in mysql.
"SELECT GROUP_CONCAT(CONCAT('<','a href=\"pagename.php?name=', title, '\"\>', title, '<', '/a>')) as name FROM YOUR_TABLE"
The above example fetch the records with comma separated value from mysql with column name name, So you will not get the error as you mentioned above. May be it will help you.

The other answer is just terrible.
We are trying desperately to make PHP users to refrain from intermixing PHP with HTML, but that answer is lowering a problem a level deeper, intermixing HTML with SQL.
While using separation from HTML you can make your code real neat
<?php
$data = $mysqli->query("SELECT name FROM users")->fetch_all(MYSQLI_ASSOC);
$last = count($data) - 1;
?>
<? foreach ($data as $i => $row) { ?>
<?= $row['name'] ?><!--
--><?php if ($i != $last) { ?>,<?php } ?>
<?php } ?>

Another way to go that you can use with your existing code is: (added 3 lines to the code, all with comment //Added this
<?php
if ($stmt1 = $mysqli->prepare("SELECT name FROM TABLE")) {
$stmt1->execute();
$res1 = $stmt1->get_result();
$hasGonePastFirst = false; //Added this
while($rwv=mysqli_fetch_array($res1)) {
if($hasGonePastFirst) echo ' , '; //Added this
else $hasGonePastFirst = true; //Added this
?>
<?php echo $rwv['name']; ?>
<?php
} } $stmt1->close(); ?>

Related

Php while codes show just 1 row

I'm using these codes.
$blog = mysql_query("SELECT * FROM blog ORDER BY id");
while($sutun = mysql_fetch_array($blog)) {
$fake = $sutun["date"];
echo "$fake";
}
When i use echo"$fake"; I can see all of my rows. But when I use <?php echo "$fake" ?> , It shows just 1 row for me.
I want to all of my rows while I'm using <?php echo "$fake" ?>.
Beacuse The echo"$fake"; in with in a loop it will echo at every iteration thats why you can see all your rows but <?php echo"$fake"; ?> executed when the loop is done so only the last row will be echoed;
You should seperate your logic like
<?php
$blog = mysql_query("SELECT * FROM blog ORDER BY id");
while($sutun = mysql_fetch_array($blog)) {
$fake = $sutun["date"];
?>
<?php
echo $fake;
}

PHP - output associate array into HTML <div>s with labels/headings

I have a PHP function that returns a single row from a localhost MySQL table like so:
<?php
//include database connection process
require_once("includes/conn.inc.php");
//prepare statement
$stmt = $conn->prepare("Select * FROM races WHERE raceID = ?");
$id = 1;
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
?>
What I would like to do with this array is output the data from the individual fields in their own HTML <div> or <p> with a heading indicating what they mean in a separate div. I currently user the print_row method that outputs everything in one. All the data I want is there, but I'd like it separated out into name/value paragraphs or divs.
//what I currently have
<?php
print_r($row);
?>
Is there a way to do this?
Thanks in advance,
Mark
I didn't understand the question very well but I think I understand what you need.
Use while to iterate trough each row.
while($row = $resultDesc->fetch_assoc())
{
echo '<p><strong>Description:</strong></p> ';
echo '<p>'. $row['description'] . '</p>';
}
That's not the exact solution but atleast shows you the path.
You can use foreach
<?php foreach ($row as $key => $val): ?>
<p><strong><?php echo $key; ?>:</strong></p>
<p>
<?php
//output relevant attribute
//of query run on page load
echo $val;
?>
</p>
<?php endforeach; ?>

Creating a table with PHP foreach function

I'm in a class called database programming. We got a data set and and put it into our servers. Now I have to use a jquery plugin to help visualize that data. I am using Graph Us plugin and trying to use the "Fill In" option.
My professor helped me create this function:
<?php
include 'connect.php';
$country_query = "SELECT DISTINCT Country FROM FemaleMaleRatioNew";
$result = mysqli_query($sql_link, $country_query);
$new_row = array();
while ($row = mysqli_fetch_assoc($result)) {
$country = $row['Country'];
$query = sprintf("SELECT Year, Value FROM FemaleMaleRatioNew WHERE Country = '%s'", $country);
$country_result = mysqli_query($sql_link, $query);
while ($country_row = mysqli_fetch_assoc($country_result) ) {
$new_row[$country][] = array('year' => $country_row['Year'],
'value'=> $country_row['Value']
);
}
}
//print_r($new_row);
?>
the print_r($new_row); is only there to make sure it works and it does, it prints out the array when activated.
He then guided me to create the table like this:
<body>
<table id="demo">
<?php foreach($new_row as $row):?>
<tr>
<td><?=$row['year'];?></td>
<td><?=$row['country'];?></td>
</tr>
<?php endforeach;?>
</table>
<script type="text/javascript">
$(document).ready(function() {
// Here we're "graphing up" only the cells with the "data" class
$('#demo td').graphup({
// Define any options here
colorMap: 'heatmap',
painter: 'fill',
// ...
});
});
</script>
</body>
What else do I need to do to get the table to work? I can't seem to figure it out. All it does is come out blank.
I'm sorry if this question isn't worded correctly or if I have not been clear on anything please let me know.
You have multiple rows for each country in your $new_row variable. You have to iterate over countries first and then over the individual rows of data:
<?php foreach($new_row as $country => $rows): ?>
<?php foreach($rows as $row): ?>
<tr>
<td><?=$country;?></td>
<td><?=$row['Year'];?></td>
<td><?=$row['Value'];?></td>
</tr>
<?php endforeach;?>
<?php endforeach;?>
Also please note that you need colon ':' not semicolon ';' after the foreach statement. This syntax (which is less known) is described here: http://php.net/manual/en/control-structures.alternative-syntax.php
If you want to display some sort of aggregate (for example sum) per country and you want to calculate it in PHP (as opposed to MySQL) you can do it like this:
<?php foreach($new_row as $country => $rows):
$sum = 0;
foreach($rows as $row):
$sum += $row['Value'];
endforeach;
?>
<tr>
<td><?=$country;?></td>
<td><?=$sum;?></td>
</tr>
<?php endforeach;?>
You should be using a single JOINed query to do this stuff, but you may not have gotten that in class yet. Since it's homework, I won't give you the flat-out answer, but here's the pseudo-code:
$countries = SELECT DISTINCT Country FROM YourTable;
while($country_row = fetch_row($countries)) {
echo $country_row['Country'];
echo <table>;
$status = SELECT Year, Value FROM YourTable WHERE Country=$country_row['Country'];
while($stats_row = fetch_row($status) {
echo <tr><td>$stats_row['Year']</td><td>$stats_row['Value']}</td>
}
echo </table>
}

mysql query within a mysql query

I'm trying to display information from a table in my database in a loop, but for certain information, I'm referencing other tables. When I try to get data from other tables, any data following will disappear. here is the code I am using:
`
//Below is the SQL query
$listing = mysql_query("SELECT * FROM Musicians");
//This is displaying the results of the SQL query
while($row = mysql_fetch_array($listing))
{
?>
...html here...
<? echo $row['name']; ?>
<? echo $row['Town']; ?>
<?
$CountyRef = $row['CountyId'];
$county = mysql_query("SELECT * FROM County WHERE CouInt='$CountyRef'");
while($row = mysql_fetch_array($county))
{
echo $row['CouName'];
}
?>
<?php echo $row['instrument']; ?>
<?php echo $row['style']; ?>`
My problem is that everything after the second while loop is not displaying. Anyone have any suggestions?
Thanks
Second loop should say $row2. $row is being overwritten. Both variables should be named different from each other.
You can acomplish that with a one single query:
SELECT *,
(SELECT CouName FROM County WHERE CouInt=mus.CountyId) as Country
FROM Musicians mus;
You final code should looks like:
<?php
$listing = mysql_query("SELECT *,
(SELECT CouName FROM County WHERE CouInt=mus.CountyId) as Country
FROM Musicians mus;");
//This is displaying the results of the SQL query
while($row = mysql_fetch_assoc($listing))
{
echo $row['name'];
echo $row['Town'];
echo $row['Country']; //Thats all folks xD
echo $row['instrument'];
echo $row['style'];
} ?>
Saludos ;)
And that?:
while($row2 = mysql_fetch_array($county)) {
echo $row2['CouName'];
}

msql fetch array no longer listing all results

I have a code that I have used over and over again before and now it's messing up. All I want to do is list information from the database into the table on the page, but now it will only show one result, instead of all the results it has found.
<table>
<tr><td style="background-color:#009745; color:#FFFFFF"><center><strong>Address Book</strong></center></td></tr>
<tr>
<?php
$getids = mysql_query("SELECT id, first_name, last_name FROM accounts WHERE s1='$id' ORDER BY id DESC", $db);
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
?>
<td><?= $ab_id ?> - <?= $ab_fn . " " . $ab_ln ?></td>
<?php
} else {
?>
<td><center>No Contacts</center></td>
<?php
}
?>
</tr>
</table>
please help me with this.
Thank You for your help :)
I love this site!! I can always get answers when I need them.
I saw two thing wrong
you are using mysql_fetch_array and later you are using string indexes to print the result
print the things in loop it is overriding values and just storing last row
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_assoc($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
echo '<td>'.$ab_id.' -'. $ab_fn.''.$ab_ln.' </td>';
}
In this messy code you're closing the while loop too early:
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
Only the last retrieved row is used later on. Also, don't use mysql_fetch_array if you're not accessing the numeric indeces of your result. Use mysql_fetch_assoc instead.

Categories