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
Related
Database_name1(Criteria) -> table_name(tenantCriteria) and inside I have the following columns
-username
-firsrent
-occupation
-age
-tenantgender
-income
-history
-address
-tenantsmk
-tenantpet
Database_name2(Tenant) -> table_name(preference) and inside I have the following columns
-username
-firsrent
-occupation
-age
-tenantgender
-income
-history
-address
-tenantsmk
-tenantpet
3.Database_name3(Ad) -> each table has the usernames name, hence table_name($username) and inside we have the following columns
-adtype
-roomtype
-negotiable
-price
-include
-title
-address1
-address2
-postcode
-city
-province
-image
-description
If the user that log in's is a tenant, and he wants to see all the property for sell, she click on the rentalmatch button and what that button is supposed to do is to check the similarities between the tenants preference table and go through all the tables in the Criteria database and return all the username from the Criteria database that have at least on similarity with the tenants preference. Once it returns all the usernames I want to go to database *(Ad) where the tables have the usernames name that we found before. We go inside that usernames table and show all the property that that user is selling.
so far this is what I have:
<?php
$conn = mysqli_connect("localhost", "root", "root");
$sql = "
SELECT t.username
FROM Criteria.tenantcriteria AS t
JOIN Tenant.preference AS p
ON t.firstrent = p.firstrent OR t.occupation = p.occupation OR t.age = p.age
OR t.gender = p.gender OR t.income = p.income OR t.history = p.history
OR t.address = p.address OR t.smoker = p.smoker OR t.pet = p.pet
WHERE p.username = $username";
$result = mysqli_query($db,$sql) or die(mysql_error());
?>
From here on out what should I do? Is the php good? if not what should it be?
This will show all the properties in an HTML list, you could use a <table> instead.
echo "<ul>";
while ($row = mysqli_fetch_assoc($result)) {
$owner = $row['username'];
echo "<li>Owner: $owner<ul>";
$owner_query = mysqli_query("SELECT * FROM Ad.$owner");
while ($property = mysqli_fetch_assoc($owner_query)) {
echo "<li><dl>";
foreach ($property as $col => $val) {
echo "<dt>$col</dt><dd>$val</dd>";
}
echo "</dl></li>";
}
echo "</ul></li>";
}
echo "</ul>";
I've had this problem for a little while and probably didn't ask the question properly last time. Having dabbled again I'm still very much confused and stuck.
I have a MySQL table that I list out a series of checkboxes based on values in this (around 200).
I have another MySQL table where a user will store their preferences, when the list loads I wish for the items that the user had previously selected in the second MySQL table to be checkboxes that have the check mark already assigned indicating previous choice. If you could please take a look at the following and point me in the right direction I'd be grateful.
$result = mysql_query("SELECT `car` FROM `carlist` ORDER BY variety ASC");
$result2 = mysql_query("SELECT `car` FROM `lists` WHERE `username` = 'Palendrone' ORDER BY variety ASC");
if (!$result) {
die("Query to show fields from table failed");
}
if (!$result2) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
}
$fields_num2 = mysql_num_fields($result2);
for($j=0; $j<$fields_num2; $j++)
{
$field2 = mysql_fetch_field($result2);
}
while($row = mysql_fetch_row($result))
{
while($row2 = mysql_fetch_row($result2))
{
if("$row2[0]" <> "$row[0]")
{?><input type="checkbox" value="<?php echo "$row[0]"?>" name="<?php echo "$row[0]"?>" id="<?php echo "$row[0]"?>">
<label for="<?php echo "$row[0]"?>"><?php echo "$row[0]"?></label>
<?php
} else
{?><input type="checkbox" value="<?php echo "$row[0]"?>" name="<?php echo "$row[0]"?>" checked="yes" id="<?php echo "$row[0]"?>">
<label for="<?php echo "$row[0]"?>"><?php echo "$row[0]"?></label>
<?php
}
} /* end while */
} /* end while */
I figured the first While loop to load the main 200 items in, then for each input in that table it cross checks against the users selection table in the second while loop, in that loop I have the if statement working in reverse order so as not to check it then uncheck it.
I was pointed in the way of starting from scratch last week by another user on here, although I've started going through some tutorials I kinda need to get this last part of my project nailed...
I would suggest changing your query strategy - use only one instead of two. You can check the value of second member of select list - lists.car from result of query below for null value. If it is null then checkbox is not selected otherwise it is (it is present in second table).
$result = mysql_query("SELECT `carlist`.`car`, `lists`.`car` FROM `carlist` left join `lists` on (`carlist`.`car` = `lists`.`car` and `lists`.`username` = 'Palendrone') ORDER BY `carlist`.variety ASC");
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?
I have 2 tables
Photos: stores all photo information
Gallery: stores heading and description about the gallery
I need to echo to a new page the Gallery Description, then all the photos that should be there.
but I keep getting heading and description repeating because its in the same
$row = mysql_fetch_array($result)...
then there is more that one set of photos in that gallery I need also?
anyone help or am I being to vague....
$a="SELECT * from gallery where gallery_category=".$gallery_category;
$result = mysql_query($a,$c);
while($row = mysql_fetch_array($result)) {
echo $row['gallery_name'].'<br>'.$row['gallery_description'].'<br>';
$sql="SELECT * FROM photos WHERE gallery_id =".$gallery_id." ORDER BY photos_filename";
$result2 = mysql_query($sql,$c);
while($row = mysql_fetch_array($result2)) {
echo'<a rel="example_group" href="../galleries/images/'.$row['gallery_id'].'/'.$row['photos_filename'].'" width="130" height="100"><img src="../galleries/images/'.$row['gallery_id'].'/'.$row['photos_filename'].'" height="150px" alt=""/></a>';
}
}
Actually I'll post it up here so I can use some code formatting.
Option 1 - loop within a loop
$headerquery = $db->query("SELECT * FROM tbl1");
while ($headers= $db->fetchNextObject($headerquery )) {
echo "<table><tr><th>".$headers->GalleryName."</th></tr>"; // open table create header
$detailquery = $db->query("SELECT * FROM tbl2 WHERE GalleryID=".$headers->ID);
while ($details= $db->fetchNextObject($detailquery )) {
echo "<tr><td>".$details->Photo."</td></tr>"; //loop through 2nd table and spit out photos
}
echo "</table>"; //close table
}
Option 2 - joined query with selector
$galleryheaderid = 0;
$query = $db->query("SELECT * FROM tbl1 INNER JOIN tbl2 on tbl1.ID=tbl2.GalleryID");
while ($details = $db->fetchNextObject($query )) {
echo "<table>";
if ($galleryheaderid!=$details->ID) { //spit out header row if id's don't match
echo "<tr><th>".$details ->GalleryName."</th></tr>"; //create header
$galleryheaderid = $details->ID; //set header id to gallery id so we don't show header a 2nd time
}
echo "<tr><td>".$details->Photo."</td></tr>"; //spit out gallery information even on first row since all rows include photo information
echo "</table>"; //close table
}
Something like either of these should work obviously they'll need completing properly
I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike