This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm trying to rewrite this script using PDO:
Get values from the database
mysql_select_db($database_db_FPF, $db_FPF);
$query_rsWorksMenu = "SELECT works.year, GROUP_CONCAT(workstitle.title) as titulos, GROUP_CONCAT(workstitle.id_title) as links FROM works JOIN workstitle ON works.id_year = workstitle.id_year GROUP BY works.year ORDER BY works.year DESC";
$rsWorksMenu = mysql_query($query_rsWorksMenu, $db_FPF) or die(mysql_error());
$row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu);
Show values
<ul>
<?php do { ?>
<li><span><?php echo $row_rsWorksMenu['year']; ?></span>
<ul>
<?php
$titulos = explode(",", $row_rsWorksMenu['titulos']);
$links = explode(",", $row_rsWorksMenu['links']);
foreach(array_combine($links, $titulos) as $link => $titulo){
?>
<li><span><?php echo $titulo; ?></span></li>
<?php } ?>
</ul>
</li>
<?php }while ($row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu)); ?>
</ul>
What I got so far:
Get the values from the database:
$stmt2 = $conn->prepare('SELECT works.year, GROUP_CONCAT(workstitle.title) as titulos, GROUP_CONCAT(workstitle.id_title) as links FROM works JOIN workstitle ON works.id_year = workstitle.id_year GROUP BY works.year ORDER BY works.year DESC');
$stmt2->execute();
$result2 = $stmt2->setFetchMode(PDO::FETCH_OBJ);
Show values
<ul>
<?php do { ?>
<li><span><?php echo $result2->year; ?></span>
<ul>
<?php
$titulos = explode(",", $result2->titulos);
$links = explode(",", $result2->links);
foreach(array_combine($links, $titulos) as $link => $titulo){
?>
<li><span><?php echo $titulo; ?></span></li>
<?php } ?>
</ul>
</li>
<?php }while ($row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu)); ?>
</ul>
The problem is that I don't know what to do with this line:
}while ($row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu));
UPDATE:
I change my code:
$stmt2 = $conn->prepare('...query...');
$stmt2->execute();
$result2 = $stmt2->fetchAll();
}while ($row_rsWorksMenu = $stmt2->fetchAll());
But nothing happens.
UPDATE 2
I try this code:
<?php do { ?>
<li><span><?php echo $result2->year; ?></span>
<ul>
<?php
$titulos = explode(",", $result2->titulos);
$links = explode(",", $result2->links);
foreach(array_combine($links, $titulos) as $link => $titulo){
?>
<li><span><?php echo $titulo; ?></span></li>
<?php } ?>
</ul>
</li>
<?php }while($result2 = $stmt2->fetch()); ?>
And my DOM show the correct numbers of <li>. But no values. Why?
The easiest way would be something like this:
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
The PDO query method returns a PDOStatement which you can iterate directly.
http://www.php.net/manual/de/pdo.query.php
Drop your while loop completely. You also don't need to prepare a statement separately since your query doesn't use any query parameters.
Do this instead:
// Get all your DB results in one place
$rsWorksMenu = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
And later, to display the results:
<?php if ($rsWorksMenu):?>
<ul>
<?php foreach($rsWorksMenu as $r):
$links_titulos = array_combine(
explode(",", $r->titulos),
explode(",", $r->links)
);
?>
<li><span><?=h($r->year)?></span>
<?php if ($links_titulos):?>
<ul>
<?php foreach($links_titulos as $link => $titulo):?>
<li><span><a href="works.php?id=<?=h(urlencode($link))?>"><?=h($titulo)?>a></span></li>
<?php endforeach // $links_titulos?>
</ul>
<?php endif //$links_titulos?>
</li>
<?php endforeach // $rsWorksMenu?>
</ul>
<?php endif // $rsWorksMenu?>
You should change your sql statement also--it will break if any of your links or titles have commas in them. (GROUP_CONCAT is generally a bad idea).
Instead, collect the ungrouped values and group them in a php array yourself, as in the get_worksmenu function below:
<?php
function get_worksmenu(PDO $db) {
$rsWorksMenu = array();
$sql = 'SELECT works.year, workstitle.title AS titulos, workstitle.id_title AS links '
.'FROM works INNER JOIN workstitle USING (id_year) ORDER BY year DESC';
// Could this be a single-table query instead?
// SELECT id_year AS year, title AS titulos, id_title AS links
// FROM workstitle ORDER BY id_year DESC
$rs = $db->query($sql);
$rs->setFetchMode(PDO::FETCH_ASSOC);
foreach ($rs as $r) {
// calculating url here simplifies your display code
// and makes it easy to change urls later
$year = $r['year'];
$r['url'] = '/works.php?id='.urlencode($r['links']);
unset($r['year']);
$result[$year][] = $r;
}
$rs->closeCursor();
return $rsWorksMenu;
}
function h($s) {
// escape a string for html
return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
$rsWorksMenu = get_worksmenu($conn);
<?php if ($rsWorksMenu):?>
<ul>
<?php foreach($rsWorksMenu as $year => $works):?>
<li><span><?=h($year)?></span>
<ul>
<?php foreach($works as $work):?>
<li><span><?=h($work['titulos'])?></span></li>
<?php endforeach //$work?>
</ul>
<?php
</li>
<?php endforeach // $rsWorksMenu?>
</ul>
<?php endif // $rsWorksMenu?>
Related
I want to print sql result in list using php.
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
while ($row = $q->fetch_assoc()) {
$hh=$row['name'];
}
?>
<ul id="myUL">
<li><?php echo $hh ?></li>
</ul>
like:-
.Mango
.Apple
.Banana
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
echo "<ul id="myUL">";
while ($row = $q->fetch_assoc()) {
echo "<li> <a href='#'>".$row['name']."</a></li>";
}
echo "</ul>";
?>
Generate the HTML in the for loop
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
$hh = ''; //empty string first
while ($row = $q->fetch_assoc())
{
$hh .= '<li>' . $row['name'] . '</li>';
// ^--------------------- concat with the previous result
}
?>
<ul id="myUL">
<?php echo $hh; /* display */ ?>
</ul>
$hh will be the last fetched value because it's being rewritten on every loop cycle. You need to append to that instead. Take a look at this:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query = "SELECT name FROM tablename";
$query = mysqli_query($con, $query)or die("Failed to fetch data");
$lis = "";
// as long as row is not empty
while ($row = $q->fetch_assoc()) {
$lis .= "<li> <a href='#'>".$row['name']."</a></li>";
}
echo "<ul>$lis</ul>";
?>
The issue is that $hh is always the last row since while($row = $q->fetch_assoc()) over writes the value of the variable with each row.
In order to output a column value in each row, you need to place the output inside of the while loop: it will do it once for each record.
You can use conditional statements for readability:
<!-- Start of List -->
<ul id="myUL">
<?php
$query = "select name from plant ";
$q = mysqli_query($con,$query) or die("Could Not Perform the Query");
while ($row = $q->fetch_assoc()):
?>
<!-- Option -->
<li><?= $row['name']; ?></li>
<?php endwhile; ?>
</ul>
<!-- End of List -->
Like referenced by #Cid in the comments, each element needs to be added inside of the list. Keep your <ul> outside of the loop.
In pseudo code, so you can understand better, it would look like this:
list
foreach row do:
output option
end foreach
end list
I have searched for about 4 hours today on how to do this.
I want to pull all post titles and categories from the posts table and
essentially want to list the "Funny" category and then list all post that have the funny category under that category. Right now I am getting the following:
Funny
-post title
Funny
-post title
I want to output
Funny
-post title
-post title
<?php
$query = "SELECT post_category,post_title FROM posts ";
$select_categories_sidebars = mysqli_query($connection, $query);
?>
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-12">
<ul class="list-group">
<?php
while($row = mysqli_fetch_assoc($select_categories_sidebars)) {
$post_title = $row['post_title'];
$post_tags = $row['post_category'];
echo "<li class='list-group-item'>$post_tags</li><ul>";
echo "<li class='list-group-item'><a href='category.php?category=$post_title'> {$post_title}</a></li></ul>";
}
?>
</ul>
That should do the trick:
First you should sort your query by category:
$query = "SELECT post_category,post_title FROM posts ORDER BY post_category";
Then do this:
<?php
while($row = mysqli_fetch_assoc($select_categories_sidebars)) {
$post_title = $row['post_title'];
$post_tags = $row['post_category'];
$used_tag = null,
// check if you already posted that category/tag. If not, show it:
if($used_tag!=$post_tags) {
echo "<li class='list-group-item'>$post_tags</li>"; // I removed a '</ul>' here
// set this title as 'used'
$used_tag=$post_tags;
}
echo "<li class='list-group-item'><a href='category.php?category=$post_title'> {$post_title}</a></li>"; // I removed a '</ul>' here too
}
?>
BUT
In an ideal world you'd have two tables to accomplish this.
One for the categories, one for the posts. Each table with id's to work with
This way you produce a lot of redundant data, it's more complicated to filter, and so on...
You might want to have a look at relational database design.
Well I basically got it working how I want I just need to format it correctly now, but it is working with some help from this question. PHP Group sql query under the same title
<?php
$query = "SELECT post_category,post_title FROM posts ORDER BY post_tags";
$select_categories_sidebars = mysqli_query($connection, $query);
?>
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-12">
<ul class="list-group">
<?php
$title = "";
while ($row = mysqli_fetch_array($select_categories_sidebars)) {
if ($row['post_category'] != $title) {
echo '<li class="list-group-item">'.$row['post_category'].'</li><br>';
$title = $row['post_category'];
}
echo '<li class="list-group-item">'.$row['post_title'];
}
?>
I am doing PM system for my site. I created subpage for each conversation by two users. I am having hard time programming the front page, where all conversations are printed. I cant get only one and last meassage for each user.
Here is my function:
public function fetch_data($id_uporabnika) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM zs WHERE za = ? ORDER BY datum");
$query->bindValue(1, $id_uporabnika);
$query->execute();
return $query->fetchAll();
}
And here is my code for printing conversations:
<?php
} else {
$zs = new Zs;
$id_uporabnika = $trenutni['id'];
$zsji = $zs->fetch_data($id_uporabnika);
?>
<h2>Zasebna sporočila</h2>
<ul class="vsi-zsji">
<?php foreach ($zsji as $sporocilo): ?>
<?php $od = $oseba->fetch_data($sporocilo['od']) ?>
<li>
<a href="<?php echo $url; ?>zs/poglej/<?php echo $sporocilo['od']; ?>">
<img src="<?php echo $url; ?>inc/timthumb.php?src=<?php echo $od['slika_potem'] ?>&w=60&h=60" alt="">
<p><b><?php echo $od['uporabnisko_ime'] ?></b></p>
<p><?php echo $sporocilo['vsebina'] ?></p>
</a>
</li>
<?php endforeach ?>
</ul>
<?php } ?>
I get 10 PMs from one user, 3 for another. I want to display just the latest one.
Just put a LIMIT clause in your SQL query and order by DESC to get the latest message:
$query = $pdo->prepare("SELECT * FROM zs WHERE za = ? ORDER BY datum DESC LIMIT 1");
something like this should help
SELECT id,datum, max(pm) FROM zs WHERE za = ? group by id,datum
I've got a query that loops through some product names and puts them down on the page. As part of the loop, it adds a comma to the end, so it looks like this:
Products: Shirts, Pants, Ties, Jackets,
Notice that I'm getting a comma after the last product. Also, they are all links, so I can't use some strreplace fx or similar:
Here's my code:
<?php
$product_query = mysql_query("select * from products_table);
$row_product_query = mysql_fetch_assoc($product_query);
$totalRows_product_query = mysql_num_rows($product_query);
?>
<strong>Products: </strong>
<?php if ($totalRows_product_query > 0) { ?>
<?php do { ?>
<span><?php echo $row_product_query['products_name']; ?></span>
<strong>, </strong>
<?php } while ($row_product_query = mysql_fetch_assoc($product_query)); ?>
<?php } ?><br />
What do I need to do to make that last comma not appear?
Thanks in advance as always.
using the php implode function
<?php
$str = "";
$product_query = mysql_query("select * from products_table");
$row_product_query = mysql_fetch_assoc($product_query);
$totalRows_product_query = mysql_num_rows($product_query);
$cnt = 0;
?>
<strong>Products: </strong>
<?php if ($totalRows_product_query > 0) { ?>
<?php do {
$arr[$cnt] = '<span>'.$row_product_query['products_name'].'</span>';
$cnt++;
<?php } while ($row_product_query = mysql_fetch_assoc($product_query)); ?>
<?php }
echo implode("<strong>,</strong>",$arr);
?><br />
Fix how they are being stored/entered into the database?
otherwise,
<?php echo str_replace(",", "", $row_product_query['products_name']); ?>
should work
As #tucker said, you could use the implode function. Implode Function. You would use it with an array like so
$a_string = implode(",",$the_result_array);
This would give you your desired results.
Following on from a question earlier today this answer was given to read the data into an array and separate it to print vehicle type and then some data for each vehicle.
<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
This is almost perfect for what I want to do but I need to print out two columns from the database ie ford and mondeo before going into the second foreach loop. I've tried print $rows['model'] and all the other combinations I can think of but that doesn't work. Any help much appreciated
I'm a bit confused by your question but the SELECT * in the SQL statement means that every column from the database should be present as a key=>value pair in the $row array. So if you needed another "column," output here into an HTML list element <li>, you just echo (note: not "print") that column name as an array key. So if you needed the type of the car column found in a column with the name "model" you'd do this:
<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<li><?php echo $vehicleData['model'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
EDIT: I'm still unclear on your question, but if every car has the same vehicleType, and you're just looking to grab that once before looping through all the results, I'm guessing this will do it:
<?php
// Set up a SQL query to grab one row
$query_to_grab_only_vehicle_type = "SELECT vehicleType FROM apparatus WHERE 1 LIMIT 0,1";
// Fetch that row and turn it into an array
$vehicle_type_array = mysql_fetch_array(mysql_query($query_to_grab_only_vehicle_type));
// Initialize a variable with the array value that came from the vehicleType column
$vehicle_type = $vehicle_type_array['vehicleType'];
// You could uncomment and use the following to echo out the variable
// echo "Vehicle type: $vehicle_type";
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<li><?php echo $vehicleData['model'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>