Sort array with two infos | PHP - php

I made code which loads online players from game server(through MySQL table). Now, I'm newbie in PHP and I don't Know how to sort them(users) in table by ID. I googled and I found answer which will sort arrays by value(1, 2, 3, 4 etc..). Only problem is because users, with ID, have a name. How to connect user's name with ID, so they stay together after sort?
Here's a code
while($_hsync_podatci = $_hsync_rezultat->fetch_assoc())
{
?>
<tr class="_hsync_online_stil_<?php echo $_hsync_dio; ?>" id="_hsync_na_mrezi_<?php echo $_hsync_podatci['ServerID']; ?>">
<td><?php echo $_hsync_podatci['ServerID']; ?></td>
<td><?php echo $_hsync_podatci['Ime']; ?></td>
<td>
<button type="button" id="_hsync_izbaci_<?php echo $_hsync_podatci['ServerID']; ?>" class="btn btn-danger" onclick="_hsync_izbaci(<?php echo $_hsync_podatci['ServerID']; ?>)" style="float: right;">
<span class="glyphicon glyphicon-log-out"></span>Izbaci
</button>
</td>
</tr>
<?php
$_hsync_dio = !$_hsync_dio;
}
Above while is table's header. Var $_hsync_dio is for background color. One row is white, second is grey, and so on.

When doing a MySQL query you can sort the array automatically when fetching the data for example:
$players = mysqli_query($conn, "SELECT * FROM playerTable ORDER BY id ASC");
while($row = mysqli_fetch_assoc($message_sender_info)){
$message[] = $row;
}
Use DESC instead of ASC for e reverse sorting.

Related

"Issue with updating a record using a button”

When I click on the update button, the SQL query updates the last record not the wanted one
when displaying several courses, I would like to give the user the right to confirm one of the courses, when I click on the update button, it updates the last record
<?php
$cc = mysqli_query($mysqli, "SELECT * from course WHERE c_email ='$emailu' AND course_situation='pending'");
while($ccc = mysqli_fetch_array($cc)) {
$idcourse = $ccc['idcourse'];
$city = $ccc['idville'];
$pickup = $ccc['course_depart'];
?>
<tr>
<td><?= $idcourse ?></td>
<td><?= $pickup ?></td>
<td><?php echo $ccc['course_date'] ?>, <?php echo
$ccc['course_heure'] ?></td>
<td>
<?php
if($ccc['course_situation'] == "pending") { ?>
<span class="badge badge-danger">Pending</span>
<?php } else { ?>
<span class="badge badge-success">Confirmed</span>
<?php } ?>
</td>
<td><?php echo $ccc['c_phone'] ?></td>
<td><?php echo $ccc['c_phone'] ?></td>
<td><?php echo $ccc['idclient'] ?></td>
<td>
<button type="submit" name="cancelcourse" class="btn btn-danger btn-xs"><i class="icon md-check" aria-hidden="true"></i> Update</button>
</tr>
<?php }
if(isset($_POST["cancelcourse"])) {
$query = "UPDATE course SET id='$idu' AND course_situation='confirmed' WHERE idcourse='$idcourse' ";
if(mysqli_query($mysqli, $query)) {
echo "<div class=' alert alert-success' style='padding-left:150px'>
<strong>Success!</strong> Event page updated.</a>.
</div>";
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index.php">';
} else {
echo "<div class='alert alert-danger'>
<strong>ERROR!</strong> We invite you to try Again Later.
</div> " . mysqli_error($mysqli);
}
}
You generate button for each course, but all your buttons are equal, they don't contains any information about which course you want to update. You use variable $idcourse, but it is assigned inside while-loop that generates table - for each row that is shown this variable is changed, so after showing whole table it will contains id for last row.
Please remember, that each time your page is reloaded (like after clicking button) whole script is executed from beginning and no variables are stored, unless you pass it yourself.
Simplest solution:
1.Add id to button
<button type="submit" name="cancelcourse" class="btn btn-danger btn-xs" value="<?=htmlspecialchars($idcourse)?>">
2.Change query
$idcourseToRemove = mysqli_real_escape_string($mysqli, $_POST["cancelcourse"]);
$query = "UPDATE course SET id='$idu' AND course_situation='confirmed' WHERE idcourse='$idcourseToRemove' ";
And last advice: learn about SQL Injection and how to avoid it (like for example by mysqli_real_escape_string function)
UPDATE course SET id='$idu',course_situation='confirmed' WHERE
idcourse='$idcourse'

Cannot group table values by ID

Hey there guys/girls I have an issue I'm currently trying to work through being a novice to MYSQL / PHP. Currently I'm using Bootstrap accordion collapsible components to display HTML tables (That are reports). Here is my current table:
Current Table in MYSQL.
So as you can see the reports row contains some HTML information which are tables. I wanted to take the information and display it on a webpage assuming that every row was a different report. So I was able to do so with writing this:
<div class="accordion" id="accordionExample">
<?php
require('db.php');
$i = 0;
$sql = "SELECT `report` FROM `automation-reports`;";
$query = mysqli_query($connection, $sql);
while($row = mysqli_fetch_assoc($query))
{
foreach($row as $key => $value)
{
?>
<div class="card">
<div class="card-header" id="heading<?php echo $i ?>">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse<?php echo $i ?>" aria-expanded="true" aria-controls="collapse<?php echo $i ?>">
Report #1: 8/6/2018
</button>
</h5>
</div>
<div id="collapse<?php echo $i ?>" class="collapse" aria-labelledby="heading<?php echo $i ?>" data-parent="#accordionExample">
<div style="text-align: center;" class="card-body">
<h3 style="float: left;"> Rating-Pull: </h3>
<?php
$i++;
echo $key;
echo "$value";
?>
</div>
</div>
</div>
<?php
}
}
?>
</div>
Which is great because it does what I thought I wanted it to do , which is this:
Display Output
What's not so great is now I realize that multiple reports are going to be in one accordion "folder" which is where the reportid row comes into play. So lets say I run my program and two (different) reports run on it but I want it in the say "folder" on the webpage. Both of these get labeled with a reportid of 1.
So what I want to do is loop through reports and then if they have the same ID group them together in that folder and iterate through the whole table like that. So that's the part where I have attempted to do so with a nested loop and SELECT 'report' FROM 'automation-reports' WHERE 'reportid' = '$i' ; and I just ended up getting the first element. Could somebody give me a hand with this and a good explanation so I can understand and learn what's happening?
Thank you!
EDIT:
Maybe a visual would be better?
VISUAL
I think GROUP BY and GROUP_CONCAT are what you are looking for.
SELECT `reportid`, GROUP_CONCAT(`report` SEPARATOR '') as report
FROM `automation-reports`
GROUP BY `reportid`
shoud do the job.
SELECT *
FROM `automation-reports`
GROUP BY `reportid`
will give you one row for each id ie.
id 1,
id 2,
id 3
Or do you want to display each row like so?
id 1, id 1,
id 2,
id 3, id 3,
id 4
if so here is a possible example of combining the reports in a loop first
$sql = "SELECT reportid, GROUP_CONCAT(report SEPARATOR ',') as reports FROM `automation-reports` GROUP BY `reportid`;";
while($row = mysqli_fetch_assoc($query)) {
echo "<div id='{$row['reportid']}'>";
echo $row['reports'];
echo "</div>";
}
I know this isn't the HTML you're after but you should be able to place your HTML in this code

Slow performance while fetching data

My website is performing very slow and taking lot of time to load the data.
Its like 2-3 mins to load the data. Can you please suggest me how to make it fast. I am fetching data from multiple table. The database has many entries almost 25000 entries.
Below Is the Code I am currently using.
<table class="table table-striped table-bordered bootstrap-datatable datatable">
<tbody>
<?php // get all state
$sql=" SELECT bm.bank_name,b.bank_ifsc,e.emp_id,e.emp_code,
e.first_name,e.middle_name,e.last_name,
e.active_status as emp_status,
e.account_no FROM tblemployee e
Left Join tblbank_mst bm on bm.bank_id=e.fk_bank_id
Left Join tblbank b on b.bank_ifsc_id=e.fk_bank_ifsc_id
where e.del_status=0
and e.role_id=4
and e.is_admin=0 ";
if($_SESSION["loggedin_role_id"]==2)
{
$sql.=" and e.added_by=".$_SESSION["loggedin_emp_id"];
}
$sql.=" order by first_name";
// echo $sql; exit;
if(mysql_num_rows($result = mysql_query($sql))>0)
{
while($row = mysql_fetch_array($result))
{ ?>
<tr>
<td><?php echo $row['emp_code'];?> </td>
<td><?php echo $row['first_name'].' '.$row['middle_name'].' '.$row['last_name'];?> </td>
<td><?php echo $row['bank_name'];?> </td>
<td><?php echo $row['account_no'];?> </td>
<td><?php echo $row['bank_ifsc'];?> </td>
<td class="center">
<?php if($row['emp_status']==1){ ?>
<span class="label label-success">Active</span>
<?php }else{?>
<span class="label label-danger">Inactive</span>
<?php }?>
</td>
<td class="center">
<!--<a class="btn btn-success" href="#">
<i class="halflings-icon white zoom-in"></i>
</a>-->
<?php if($row['approve_status']==0){ ?>
<a class="btn btn-info" href="edit_employee.php?emp_id=<?php echo $row['emp_id'];;?>">
<i class="halflings-icon white edit"></i>
</a>
<a class="btn btn-danger" href="#" onClick="ConfirmDelete(<?php echo $row['emp_id'];?>)">
<i class="halflings-icon white trash"></i>
</a>
<?php }else{ echo "--"; }?>
</td>
</tr>
Assuming your largest table is tblemployee, try creating a compound index on the three columns mentioned in your WHERE clause, which is:
WHERE e.del_status=0 and e.role_id=4 and e.is_admin=0
You can do this with
CREATE INDEX emp_del_role_admin
ON tblemployee
(del_status, role_id, is_admin);
Why does this help? Because MySQL's query planner can random-access the index to find the first row of your table matching your WHERE statement, then it can read the index sequentially to find the rest of the matching rows.
Of course, if your WHERE filter matches many thousands of rows in your table, you will still have a slow page; it takes time to load, transmit, and render a very large page.
If you are trying to display 25000 (or too many) entries in one time :
This is slow and that's normal, you should paginate your results : use some infinite scroll plugin to display the same thing and limiting results for each query -EDIT : or DataTable pagination options-.
If you are not
First you should have a look at slow queries , configuration to change in my.cnf file.
If your query is slow, you may then optimize your query by adding INDEX where you have to. You should use EXPLAIN (documentation) to help you doing this.
Be sure you have foreign keys declared as foreign keys (bm.bank_id & e.fk_bank_id - b.bank_ifsc_id & e.fk_bank_ifsc_id), that will speed up your query. Adding index on things like e.role_id could do it aswell.
Only you can know which index to add in this case.
Do not use PHP's mysql_* interface; switch to either mysqli_* or PDO.
Add two composite indexes:
(del_status, role_id, is_admin, first_name)
(del_status, role_id, is_admin, added_by, first_name)
The first handles the case where you skip the additional AND.
The following pattern may help performance more: Change
... bm.bank_name,
...
Left Join tblbank_mst bm ON bm.bank_id=e.fk_bank_id
to
... ( SELECT bank_name FROM tblbank_mst WHERE bank_id=e.fk_bank_id
) AS bank_name,
...
Ditto for the other LEFT JOIN.
Please see this answer as it might help you:
https://stackoverflow.com/a/35757120/1276062
In short you should check if you have indices on theese columns:
tblbank_mst.bank_id
tblemployee.fk_bank_id
tblbank.bank_ifsc_id
tblemployee.fk_bank_ifsc_id
tblemployee.del_status
tblemployee.role_id
tblemployee.is_admin
tblemployee.added_by
first_name
If the indices won't help you should run EXPLAIN on the query and post the results into the question

how to associate two tables in query? [duplicate]

This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
I saved a value as a cookie and then checked if there exists in the perfiles_vinculados table to get all the data that has the same id in the perfil table.
Then I create an array of the $vinculado result and show it in a HTML table as a row.
The problem is that the console returns:
Catchable fatal error:
Object of class mysqli_result could not be converted to string in
C:\xampp\htdocs\miramonteapp\api\modal.php
The cookie:
document.cookie = "vinculaciones=" + $("#mod_id_perfil").val();
PHP:
//querys
<?php
include 'api/conexion.php';
$ides = $_COOKIE['vinculaciones'];
$juridicos = "SELECT perfil_juridica FROM perfiles_vinculados where perfil_fisica = '$ides'";
$con = mysqli_query($conexion, $juridicos);
$vinculado = mysqli_query($conexion, "SELECT * FROM perfil where id = '$con'");
?>
//table
<?php
while($reg = mysqli_fetch_array($vinculado)) {
$id = $reg['id'];
?>
<tr id="<?php echo " tr_ ".$reg['id']; ?>">
<td class="" data-id="<?php echo $reg['usuario'] ?>">
<?php echo $reg['nombre']; ?>
</td>
<td class="" data-id="<?php echo $reg['usuario'] ?>">
<?php echo $reg['cuit']; ?>
</td>
<td class="td-actions text-right">
<button type="button" rel="tooltip" class="btn btn-danger">
<i class="material-icons">close</i>
</button>
</td>
<?php } ?>
You have to learn about join sql statement.
As for you current approach, first you need to fetch perfil_juridica value from a result of $juridicos execution and then pass this value to your second query:
// first query
$juridicos = "SELECT perfil_juridica FROM perfiles_vinculados where perfil_fisica = '$ides'";
$result = mysqli_query($conexion, $juridicos);
$row = mysqli_fetch_array($result);
$perfil_juridica = $row['perfil_juridica'];
// second query
$vinculado = mysqli_query($conexion, "SELECT * FROM perfil where id = '$perfil_juridica'");
What you should do next is move to prepared statements instead of putting unsafe values into query texts. This question will help you.

Show Three records of MySql table in three columns of html table Using PHP

I Need to show three records of MySql table in three different column using php.My Query is
SELECT * FROM TABLE1 WHERE Id IN(1,2,3)
I want to show the result as here
How can i Write LOOP for it?like
while(loop condition)
{
//what will go here?
}
UPDATE: First row fields will show in first column of html table and second record fields will display in second column and so on...I am not asking only show three records
OP saying, it's not so simple. But it is.
So, you have 2 ways to do it.
First. In this case, you are loop through on the 3 columns. Fetch the first row. This put all the data into a div. Class name is column_1. Do it for the other 3. Then floating the divs to left to each other.
$i = 1;
while($row = $db->fetch_row()) {
?>
<div class="column_<?php echo $i; ?>">
<div class="picture">
<?php echo $row["image"]; ?>
</div>
<div class="description">
<?php echo $row["desc"]; ?>
</div>
... and so on...
</div>
<?php
$i++;
}
Second one, when you first collect the data about 3 rows, and then put them into a table rows by row.
<?php
while($row = $db->fetch_row()) {
$results[] = $row;
}
?>
<table>
<tr>
<td><?php echo $result[0]['image'] ?></td>
<td><?php echo $result[1]['image'] ?></td>
<td><?php echo $result[2]['image'] ?></td>
</tr>
<tr>
<td><?php echo $result[0]['desc'] ?></td>
<td><?php echo $result[1]['desc'] ?></td>
<td><?php echo $result[2]['desc'] ?></td>
</tr>
</table>
EDIT
I forgot that, there is a third solution. You can just build the table empty, and then you can update the cells with an ajax call with jQuery.
One way of looping through them is foreach()
assuming you have your results in $results array:
foreach($results as $result) {
//create your table
$result['id']; //has the item id
$result['title']; //has item title
//and so on...
}
HERE is a great tutorial on looping through mysql result sets :D (W3Schools)
Another one HERE
To provide a answer to your comment you must understand how HTML tables work...
<tr> = table row
<td> = table data
You are asking for an entire source code, and this is NOT that place, we don't do your job for you, but if you want, you will have to pay me :) and I am not sure that you agree with this :)
HERE is a good and easy to understand tutorial on HTML tables.
while ($data=mysql_fetch_array($rs)) {
}

Categories