How can I set fetch to show only one value, per user?
Now, my fetch shows all rows, but I want to foreach only for 1 row
Ex: Headshots row: foreach headshots row
Deaths row: Foreach deaths row
Currently my code shows every row and I can't put them into html
PHP.
<?php
include_once 'config.php';
$top_users = [];
$columns = ['Humanity', 'Headshots', 'Murders', 'BanditsKilled', 'ZombiesKilled', 'pAliveTime'];
foreach ($columns as $column) {
$query = $config->prepare("SELECT UserID, UserName, $column as num FROM users ORDER BY $column DESC LIMIT 1");
if($query->execute()) {
$top_users[$column] = $query->fetch();
}
}
?>
HTML
<div class="colw_3 spec-l border-right">
<p></p><p><strong><em><font color="white">Humanity</font></em></strong><br>
</p>
<p><strong><em><font color="white">Headshots:</font></em></strong><br>
</p>
<p><strong><em><font color="white">Bandits Killed:</font></em></strong><br>
</p>
<p><strong><em><font color="white">Murders</font></em></strong><br>
</p>
<p><strong><em><font color="white">Zombies Killed</font></em></strong><br>
</p>
<p><em><strong><font color="white">Alive Time:</font></strong></em><br>
</p>
</div>
<!-- END col_6 -->
<div class="colw_3 paddbott100 spec-r">
<p></p><p><strong><font color="white"> <?php foreach ($top_users as $column => $data) {
echo $data['UserName'] . ' ' . $data['num'] ;
}?></font></strong><br>
</p>
<p><strong><font color="white"> <?php echo $query_result["Headshots"]; ?></font></strong><br>
</p>
<p><strong><font color="white"> <?php echo $query_result["BanditsKilled"]; ?></font></strong><br>
</p>
<p><strong><font color="white"> <?php echo $query_result["Murders"]; ?></font></strong><br>
</p>
<p><strong><font color="white"> <?php echo $query_result["ZombiesKilled"]; ?></font></strong><br>
</p>
<p><strong><font color="white"> <?php echo $query_result["pAliveTime"]; ?></font></strong><br>
</p>
</div>
and instead of ?php echo $query_result["text"]; i want to add the foreach, but it shows all rows.
I think to add
foreach ($top_users as $column => $data)
{{ $row->Humanity }}
but i don't know how to type it.
I tried to do so:
<?php
include_once 'config.php';
$top_users = [];
$Humanity = ['Humanity'];
$Headshots = ['Headshots'];
$Murders = ['Murders'];
$BanditsKilled = ['BanditsKilled'];
$ZombiesKilled = ['ZombiesKilled'];
$pAliveTime = ['pAliveTime'];
foreach ($Humanity as $Humanity) {
$query = $config->prepare("SELECT UserName, $Humanity as num FROM users ORDER BY $Humanity DESC LIMIT 1");
if($query->execute()) {
$top_users[$Humanity] = $query->fetch();
}
$query = $config->prepare("SELECT UserName, $Headshots as num FROM users ORDER BY $Headshots DESC LIMIT 1");
if($query->execute()) {
$top_users[$Headshots] = $query->fetch();
}
}
?>
HTML
<div class="colw_3 paddbott100 spec-r">
<p></p><p><strong><font color="white"> <?php foreach ($top_users as $Humanity => $data) {
echo $data['UserName'] . ' ' . $data['num'] . '<br>' ;
}?></font></strong><br>
</p>
<p><strong><font color="white"> <?php foreach ($top_users as $Headshots => $data) {
echo $data['UserName'] . ' ' . $data['num'] . '<br>' ;
}?></font></strong><br>
Related
I'm currently doing a private chat (style messenger), and I got a problem..
I have a href a link which sends an ID using GET to another page, the thing is that on the other page I load a jquery script which again sends to another page, suddenly it no longer finds the ID GET, what should I do? I want to actualise the page (the messages) thanks (noted that I'm new, I'm not enough good to use ajax or something..)
message.php
message
<?php
// $allUsers = 'SELECT * FROM members WHERE name LIKE "%cc%" ORDER BY id DESC' / SEARCH MEMBERS
$allUsers = $dbh->query('SELECT * FROM members ORDER BY id DESC LIMIT 0, 5');
if ($allUsers->rowCount() > 0)
{
while ($user = $allUsers->fetch())
{
?>
<div id="s_un_main">
<div class="s_un_main_pun">
<img src="../images/avatar/<?php echo $user['avatar'];?>">
<p><?php echo $user['name']; ?></p>
</div>
<div class="s_un_main_pdeux">
<a class="private" target="_blank" href="private.php?id=<?php echo $user['id']; ?>">Message</a>
</div>
</div>
<?php
}
}
else
{
echo "<p>" . "Aucun utilisateur trouvé. " . "</p>";
}
?>
private.php
private
<div id="get_name">
<?php
// USERINFO
if (isset($_SESSION['id']) AND !empty($_SESSION['id']))
{
$getid = $_GET['id'];
$req = $dbh->prepare('SELECT * FROM members WHERE id = :getid');
$req->bindValue('getid', $getid);
$req->execute();
$userinfo = $req->fetch();
}
?>
<div>
<img id="img_header" width="50" src="../images/avatar/<?php echo $userinfo['avatar'];?>">
</div>
<?php echo "<p>" . $userinfo['name'] . "</p>"; ?>
</div>
<section id="zz">
<div id="show_msg">
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
</div>
</section>
<form id="private_form" method="POST" action="">
<textarea name="message"></textarea>
<input type="submit" name="send"></input>
</form>
<script>
setInterval('load_messages()', 1500);
function load_messages()
{
$('#zz').load('private_message.php');
}
</script>
private_message.php
error
<!-- DB -->
<?php include("../db/db.php"); ?>
<!-- DB -->
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
var_dump($getid);
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
var_dump($id) = not found
I have used foreach loop to display the rows in myphp database, however I would now like to display this in DESC order (display last row first) however research tells me not to use the SELECT command in arrays? is there another way? Many thanks.
index.php:
<?php
include("app/database/db.php");
$posts = selectAll('posts', ['published' => 1]);
?>
<?php foreach ($posts as $post): ?>
<div class="post">
<div class="col-lg-6">
<!-- HEADLINE -->
<h1><strong><?php echo $post['title']; ?></strong></h1>
<!-- TEXT BODY -->
<!-- <h4></?php echo $post['body']; ?></h4> displays the full body -->
<h4 class="mainbody"><?php echo html_entity_decode(substr($post['body'], 0, 100) . '...'); ?></h4>
<!-- IMAGE -->
<div class="col-lg-6">
<img src="<?php echo '/assets/images/' , $post['image']; ?>" style="width: 550px; height: 350px; object-fit: cover;">
</div>
</div>
<?php endforeach; ?>
db.php file:
<?php
function selectAll($table, $conditions = []) {
global $conn;
$sql = "SELECT * FROM $table";
if (empty($conditions)) {
$stmt = $conn->prepare($sql);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
return $records;
} else {
$i = 0;
foreach ($conditions as $key => $value) {
if ($i === 0) {
$sql = $sql . " WHERE $key=?";
} else {
$sql = $sql . " AND $key=?";
}
$i++;
}
$stmt = executeQuery($sql, $conditions);
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
return $records;
}
}
?>
i have 3 table T1, T2, T3,
so, in T1 i want to select 1st row and select from T2 the rows related to the row selected in T1, and select from T3 rows related to T2 how have relation with row selected in T1 and print all this in one continer withe php while loop function
see the images for more descriptions
Base on what I understand with your question. This could be the answer
<?php
$db = new PDO("mysql:host=localhost", "username", "password");
$q1 = $db->prepare("SELECT * FROM T1");
$q1->execute();
$f1 = $q1->fetchAll(PDO::FETCH_ASSOC);
foreach ($f1 as $f1_items) {
echo "<tr><td>".$f1['id_cat']."</td></tr>";
$q2 = $db->prepare("SELECT * FROM T2 WHERE id_cat = ".$f1['id_cat'].";");
$q2->execute();
$f2 = $q2->fetchAll(PDO::FETCH_ASSOC);
foreach ($f2 as $f2_items) {
echo "<tr><td>\t".$f2['id_tr']."</td></tr>";
$q3 = $db->prepare("SELECT * FROM T3 WHERE id_tr = ".$f2['id_cus'].";");
$q3->execute();
$f3 = $q3->fetchAll(PDO::FETCH_ASSOC);
foreach ($f3 as $f3_items) {
echo "<tr><td>\t\t".$f2['id_cus']."</td></tr>";
}
}
}
?>
Solved and this is the code i am happy :)
$ReqFindRows = "SELECT * FROM commandes WHERE commande_status = 0 AND date(commande_le) = CURDATE()";
$STMTFindRows = $connect->stmt_init();
if(!$STMTFindRows->prepare($ReqFindRows)){
echo "No Results";
}
else {
$STMTFindRows->execute();
$ResultsFindRows = $STMTFindRows->get_result();
$x = 0;
while($ArrayCat = $ResultsFindRows->fetch_assoc()){
switch($ArrayCat['commande_importance']){
case 0 :
$importance = 'Normal';
$bgclas = "bg-blue";
break;
case 1 :
$importance = 'Urgent';
$bgclas = "bg-yellow";
break;
case 2 :
$importance = 'Immediat';
$bgclas = "bg-red";
break;
};
$prods = array();
$GetProductsInCommandeQuery = "SELECT * FROM commandes_produits WHERE commande_id = ?";
$GetProductsInCommandeSTMT = $connect->stmt_init();
if(!$GetProductsInCommandeSTMT->prepare($GetProductsInCommandeQuery)){
echo $connect->error;
}
else {
$id_toserch = $ArrayCat["commande_id"];
$GetProductsInCommandeSTMT->bind_param("s", $id_toserch );
$GetProductsInCommandeSTMT->execute();
$GetProductsInCommandeResults = $GetProductsInCommandeSTMT->get_result();
$Prodss = "";
while($GetProductsInCommandeArray = $GetProductsInCommandeResults->fetch_array()){
$prods = $GetProductsInCommandeArray["recette_id"];
$GetSupQuery = "SELECT * FROM commandes_supp WHERE tr_number = ? AND commande_id = ?";
$GetSupSTMT = $connect->stmt_init();
if(!$GetSupSTMT->prepare($GetSupQuery)){
echo $connect->error;
}
else {
$trNumber = $GetProductsInCommandeArray["tr_number"];
$GetSupSTMT->bind_param("ss", $trNumber, $id_toserch );
$GetSupSTMT->execute();
$GetSupResults = $GetSupSTMT->get_result();
$Supp = "";
while($GetSupArray = $GetSupResults->fetch_array()){
$Suppss = $GetSupArray["supp_id"];
$Supp .= '<p style="color:#F00">'.$Suppss.' </p>';
}
}
$Prodss .=
'<tr>
<td>
'.$prods.'
'.$Supp.'
</td>
<td>
A table
</td>
<td>
<button type="button" class="btn btn-sm">Servis</button>
</td>
</tr> ';
}
}
?>
<div class="col-xs-6 col-md-4" style="margin-bottom:10px;">
<div class="tiket">
<div class="tikeheader <?php echo $bgclas ?>">
<span class="commandenumber">
<i class="fa fa-star iconheader">
</i>
<?php echo $ArrayCat["commande_id"] ?> A Table
</span>
<span class="importance">
<?php echo $importance?>
</span>
</div>
<div class="tiketbody">
<table class="tiketbodytable">
<tbody>
<?php echo $Prodss ?>
</tbody>
</table>
</div>
</div>
</div>
<?php
}
}
?>
</div>
</div>
</div>
</div>
<?php
}
?>
I have two tables one for users and one for their reviews. On one page I need to show thumbnails of each user and the reviews that match that user. The problem is the LEFT JOIN creates a row for every time there is a review. So if a user has two reviews they are showing up twice in the list of thumbnails. Do I need a loop inside the loop? Everything I can think of seems really clunky. Thanks.
// Get Data
$qry = "SELECT * FROM `users` LEFT JOIN `reviews` ON users.userId = reviews.user_id WHERE installation_id = $installation_id";
$res = mysqli_query($mysqli, $qry) or die('-1'.mysqli_error($mysqli));
//$uqry = "SELECT membership FROM users WHERE userId = $uid";
//$current_user = mysqli_query($mysqli, $uqry) or die('-1'.mysqli_error($mysqli));
$getUser = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT membership FROM users WHERE userId = $uid"));
$currentUserLevel = $getUser['membership'];
?>
<div class="container">
<div class="content">
<?php if ($msgBox) { echo $msgBox; } ?>
<div class="row">
<?php $lists = array();
while($list = mysqli_fetch_assoc($res)) {
$lists[] = $list;
}
foreach($lists as $list) {
$name = stripslashes($list['usersName']);
$bio = stripslashes($list['usersBio']);
$review = stripslashes($list['comments']);
$stars = stripslashes($list['stars']); ?>
<div class="col-md-4">
<div id = "user-square">
<div class="avatar">
<img src="<?php echo $avatarDir.$list['usersAvatar']; ?>" class="publicAvatar" />
</div>
Name:<?php echo $name; ?> <br />
Bio:<?php echo $bio; ?> <br />
Review:<?php echo $review; ?> <br />
Stars: <?php echo $stars; ?> <br />
<?php
if ($currentUserLevel == 'pro') {
echo 'CONTACT SCOUT';
}
else {
echo 'Sorry you must upgrade to a Pro membership to contact this Scout';
}
?>
</div>
</div>
<?php }
?>
</div>
</div>
</div>
</div>
Change the while loop to the following:
while($list = mysqli_fetch_assoc($res)) {
$lists[$list['usersName']][$list['usersBio']][$list['stars']][] = $list['comments'];
}
That will give you a nice multidimensional array with the user name as the first key, and all that users reviews ordered by star rating. You should probably use a unique key rather than the users name as there could be duplicates, so either the email or unique row ID would be better.
You can then (VERY basic example):
$reviews = "";
foreach($lists as $username => $array) {
foreach($array as $bio => $array2) {
$name = stripslashes($username);
$bio = stripslashes($bio);
foreach($array2 as $stars => $comments_array) {
$stars = stripslashes($stars);
foreach($comments_array as $comments) {
$reviews .= $stars . " - " . stripslashes($comments) . "<br />";
}
}
// Your HTML here using $name, $bio, and $reviews(which will be star rating followed review for that user each on a new line)
echo '
<table width="400">
<tr>
<td>' . $name . '</td><td>' . $bio . '</td><td>' . $reviews . '</td>
</tr>
</table>
';
}
$reviews = "";
}
i'm trying to paginate my results, the limit is working, the number of pages is properly set, but the links of the pagination don't work, i've been looking for a while and nothing, ¿can you take a look and tell me what i'm doing wrong? thanks
<?php
include("config/conexion.php");
$limit = 3;
if(isset($_GET['pag'])){
$pag= $_GET['pag'];
}else{
$pag=1;
}
$offset = ($pag-1) * $limit;
$sql = "SELECT SQL_CALC_FOUND_ROWS id, nombre, local, telefono, celular, email FROM almacenes WHERE id_cat = '".$_GET["id"]."'";
$sqlTotal = "SELECT FOUND_ROWS() as total";
$currentid = $_GET["id"];
$rs = mysql_query($sql);
$rsTotal = mysql_query($sqlTotal);
$rowTotal = mysql_fetch_assoc($rsTotal);
// Total de registros sin limit
$total = $rowTotal["total"];
?>
<?php if($_GET["id"]){ $cat = mysql_query("SELECT * FROM almacenes WHERE id_cat = '".$_GET["id"]."' ORDER BY id ASC LIMIT $offset, $limit"); if(mysql_num_rows($cat)>0){
while($row = mysql_fetch_object($cat)){ ?>
<div class="almacenbox">
<div class="shadow"></div>
<div class="white">
<div class="image"><img src=almacenes/local_111.jpg></div>
<div class="title"><?php echo $row->nombre?></div>
<div class="text">Local: <?php echo $row->local?></div>
<div class="text">Teléfono: <?php echo $row->telefono?></div>
<div class="text">Celular: <?php echo $row->celular?></div>
<div class="text"><?php echo $row->email?></div>
</div>
</div>
<?php } ?>
<?php } }else{ echo "<p>No hay resultados para mostrar</p>"; }?>
<table border="1" bordercolor="#000">
<tfoot>
<tr>
<td colspan="2">
<?php
$totalPag = ceil($total/$limit);
$links = array();
for( $i=1; $i<=$totalPag ; $i++)
{
$links[] = "<a href=almacenes.php?id=$currentid?pag=$i\>$i</a>";
}
echo implode(" - ", $links);
?>
</td>
</tr>
</tfoot> </table>
$links[] = "<a href=almacenes.php?id=$currentid?pag=$i\>$i</a>";
Should be
$links[] = '$i';
Query strings start with a ? but any name-value pairs after that first one require an ampersand.
On a side note you should never place user data directly into your query. This leaves you open to an SQL injection attack. Consider using mysql_real_escape_string or switching to the mysqli library.