Sorting by count using two columns - php

I am outputting some data from mysql into a div, using a php while loop and mysql_fetch_array. Which all works fine but what I am struggling with is.. I want the data to appear ascending from the count of two column rows. but the two columns are in a different table linked by a foreign key (which I set up in phpmyadmin) so at the moment I am:
$query= mysql_query("SELECT * FROM venue WHERE idLocation = $idLocation");
while($row = mysql_fetch_array($query)) {
$idVenue = $row['idVenue'];
$locationName = $row['name'];
$query_counter_resturant = "SELECT `idResturant` FROM `myTable`
WHERE `idResturant` = '$venue_id'";
$query_run_counter_resturant = mysql_query($query_counter_resturant);
$counter_resturant = mysql_num_rows($query_run_counter_resturant);
$query_counter_cafe = "SELECT cafe FROM myTable
WHERE cafe ='$venue_id'";
$query_run_counter_cafe = mysql_query($query_counter_cafe);
$counter_cafe = mysql_num_rows($query_run_counter_cafe);
$counter = $counter_resturant + $counter_cafe;
?>
<div>
<p> <?php echo $locationName ?> </p>
<P> <?php echo $counter ?> </p>
</div>
So basically I want it to be sorted by $counter ascending.. is there anyway to do this?

Related

How to create an Edit button for each row from a 2d array in PHP

I have a 2d array in php that displays the table contents and I was able to create an edit icon for each row. However, I am having trouble retrieving the data from the selected row.
Here's how I populated my array:
<?php
//use query to retrieve columns
$sql = "SHOW COLUMNS FROM $table_name";
$result1 = mysqli_query($conn, $sql);// contains the query that creates 2d
while ($record = mysqli_fetch_array($result1)) { //returns current row 1d
$fields[] = $record['0'];//takes first element from record called fields (table names)
}
//retrieve the table content since data table has rows and columns
//lets use 2d array
$data2dArr = array();
//retrieve all columns without listing them explicitly, for the sort
if ($dir == 0) {
$query = "SELECT * FROM $table_name ORDER BY $fields[$cn]"; //ascending
} else {
$query = "SELECT * FROM $table_name ORDER BY $fields[$cn] DESC"; //descending
}
$result2 = mysqli_query($conn, $query);
while ($line = mysqli_fetch_array($result2, MYSQL_ASSOC)) {
$i = 0; // counter
//each element in array line
foreach ($line as $col_value) {
$data2dArr[$i][] = $col_value; // is stored in col value, dataarr used for display
$i++;
}
}
?>
First, I printed the values in my 2d array like this:
<?php
for ($j = 0; $j < count($data2dArr[0]); $j++) {
?>
<tr>
<?php
for ($k = 0; $k < count($fields); $k++) {
?>
<td><?php print $data2dArr[$k][$j]; print $j;? </td>
<?php
}
//added the Edit button here
?>
<th><input type="image" src="images/edit.png" onclick="openForm()"/</th>
<?php
}
?>
In my edit.php file, I have the same array above but inside the 2nd for loop, contains:
<td><input name="field<?php echo $k ?>" id="field<?php echo $k ?>" placeholder="<?php print $data2dArr[$k][$j] ?>" class="full-width" type="text"> </td
the purpose is print the selected row x that contains y columns but the solution above prints out all of the elements. I know that it's because all contents in my table are being put in my input<> for each iteration, what I cannot figure out is how to print just the fields of the column from selected row.
For example,
From the table called Student
student_number | name | class| major |
22 | Rick | 3 | CS | editButton
32 | Ross | 5 | Math | editButton
If I select the student number from the second row, I expect my input placeholder to have |32|Ross|5|Math
I would like to know how do I go about this? Any advice would be very helpful.
You question is kinda long and confusing so I assume you have problem to print specific
field in the array?
You can try:
foreach($data2dArr as $key => $value){
print $data2dArr[$key]["student_number"]."|".$data2dArr[$key]["name"]."|".$data2dArr[$key]["class"]."|".$data2dArr[$key]["major"];
}
It is better to show less of your code and explain briefly yet clearly what are you trying to achieve

How to display multiple names from different Database tables

I"m trying to display names that connected to the same table.
There are 3 different DB tables:
Tables
Guests
Info
First I get the data from the "Table" to get the table id.
Than I get the data from the "Info" table to figure which guests are connected to the table id so I get their id's (can be multiple id's).
And last I get the name of every guest by it's id.
My issue is that I can only get the final name I'm expecting and not all names that are connected to the same table.
The last result needs to display each table and every name that connected to table.
PHP:
$sql_e1 = "SELECT `tid` FROM `table`";
$result_e1 = $con->query($sql_e1);
if ($result_e1->num_rows > 0) {
$i = 0;
while($row0 = $result_e1->fetch_assoc()) {
$table_id = $row0['tid'];
$array[$i]['table_id'] = $table_id;
$sql_e2 = "SELECT `id` FROM `info` WHERE `tid`='".$table_id."'";
$result_e2 = $con->query($sql_e2);
if ($result_e2->num_rows > 0) {
while($row2 = $result_e2->fetch_assoc()) {
$guest_id = $row2['id'];
$array[$i]['guest_id'] = $guest_id;
$sql_e3 = "SELECT `name` FROM `guests` WHERE `id`='".$guest_id."'";
$result_e3 = $con->query($sql_e3);
if ($result_e3->num_rows > 0) {
while($row3 = $result_e3->fetch_assoc()) {
$array[$i]['name'] = $row3['name'];
}
}
}
}
$i++;
}
}
$counter = 0;
HTML:
<?
if (isset($i)) {
while ($counter < $i) {
include 'infodialog.php';
?>
<div class="<? echo $array[$counter]['table_id']; ?>">
<p><? echo $array[$counter]['name']; ?></p>
</div>
<?
$counter++;
} } ?>
If you want to get multiple names in array your code should be:
$array[$i]['name'][] = $row3['name'];
Or according guest ids code should be
$array[$i][$guest_id]['name'][] = $row3['name'];
This will get all the names but you have to change your HTML code according array.
Another solution besides Rohit Rasela's is using JOINS. JOINS will be a much better solution in the long run especially when you start adding a lot of data and speed is important. It's been a while since I've done PHP and MySQL and I haven't tested this but it should work I believe:
MySQL:
SELECT
guests.name as GuestName,
table.tid as TableId,
info.id as InfoId
FROM table AS table
JOIN info AS info ON info.tid = table.tid
JOIN guests AS guests ON guests .id = info.[guest_id_column_name]
This will return a row for each match it finds when it goes through each table and you'll be able to loop through and access the GuestName, TableId and InfoId for each match. If you don't care about the table ids, you can leave them out in the SELECT list. You can add ORDER BY if the order matters.
HTML loop:
while ($row = $result->fetch_assoc()) {
<div>Guest name: <php echo $row['GuestName']; ?></div>
<div>Table Id: <php echo $row['TableId']; ?></div>
<div>Info Id: <php echo $row['InfoId']; ?></div>
}
You can get more information on JOINs at https://www.w3schools.com/sql/sql_join.asp

I want to fetch first five rows and display same 5 five rows at different places on single page using single query

I want to fetch first five rows and display same five rows at different places on single page, using single query
$cel_bir1=$db->query("SELECT * FROM tbl_birthday WHERE MONTH(Birthday_Date)=$month AND DAY(Birthday_Date)=$day LIMIT 4");
$get_bir=$cel_bir1->fetch(); $count=0;
while($get_bir1=$cel_bir1->fetch())
{
if($count++) echo ',';
echo $get_bir1['Name'];
}
So to get the first 5 rows, you can use Mysql Limit eg: Select * FROM mytable LIMIT 5.
Ok, typically what happens is, When using a PDO,your result-set is stored in an array.
$query = "Select * FROM mytable";
$statement = $db->prepare($query);
$statement->execute();
$productsinfo = $statement->fetchAll();//$productsinfo is the array in question
$statement->closeCursor();
Now to get the values in the array, you can loop through the array using a foreach loop like:
foreach($productsinfo as $productsinfomation):
$productid=$productsinfomation['productid'];
//you can echo $productid or anything you want to do with it here
endforeach;
There is no harm in repeating the foreach loop at different positions on your page.
Le'me know how it works for you.
Have fun coding.
$sql ="SELECT * FROM table_name LIMIT 0,5";
// $conn = your connection to database
$result = $conn->query($sql) or die($conn->error);
$html = '';
while($row = $result->fetch_assoc()){
$html.= $row['colum1'].'<br>'.$row['colum2'];
}
echo $html;
?>
// some more html code
<?php echo $html?>
// some more html code
<?php echo $html?>
// some more html code
<?php echo $html?>

shuffle : Display only one row at the same time

How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.

How to display the content of more then one SQL database row

I am trying to retrieve the data stored in an unknown number of mySQL database rows and display them using HTML. At the moment I can display data from one row.
Each row has a unique id number, I was planning to iterate through by comparing this number to the variable counter. But it would then leave me with the issue of displaying the results in HTML. At the moment I am just echoing variables that contain data from the rows. However what I want to create is a HTML list that increases in length depending on how many rows are in the table.
Here is my current PHP code for retrieving a row from the database is:
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
$row = $query->fetch_assoc();
$task_id = $row["task_id"];
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_importance = $row["task_importance"];
$task_description = $row["task_description"];
$task_deadline = $row["task_deadline"];
$task_members = $row["task_members"];
$task_budget = $row["task_budget"];
At the moment I am just displaying some of the results in HTML using this code:
<div id="inner_container">
<?php echo "$task_id $proj_name $task_name $task_deadline"; ?>
</div>
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
while($row = $query->mysqli_fetch_assoc()) {
$task_id = $row["task_id"];
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_importance = $row["task_importance"];
$task_description = $row["task_description"];
$task_deadline = $row["task_deadline"];
$task_members = $row["task_members"];
$task_budget = $row["task_budget"];
echo "$task_id $proj_name $task_name $task_deadline";
}
Since you have built an associative array using fetch_assoc all you need to do is loop through that array. The OO example on http://php.net/manual/en/mysqli-result.fetch-assoc.php should get you what you need. A quick example:
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
echo '<div id="inner_container">';
while ($row = $query->fetch_assoc()) {
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_deadline = $row["task_deadline"];
echo "$task_id $proj_name $task_name $task_deadline";
};
/* free result set */
$row->free();
echo '</div>;

Categories