MYSQL select where column value matches another value in same column - php

I have a database table that contains values where the meta_id corresponds to the data in the meta_data column. But now i want to display that data inside a bootstrap table.
I have a table like so in php myadmin
I would like the result to look like this:
I currently have this query written up but im confused about how to best do this.
I thought by counting the rows that exist and then dividing them by the table header count i should get table row loop that i can then insert my table columns into but its still creates more columns than i need.
<?php
$sql="SELECT * FROM table WHERE pid=".$this->item->id." ORDER BY meta_data ASC";
$db->setQuery($sql);
$db->query();
$count=$db->getNumRows();
$meta= $db->loadObjectlist();
foreach($meta as $data){
$metadata .= '<td>'.$data->meta_data.'</td>';
}
$count = $count/2; // i know there will be only two th's
?>
<table class="table table-striped">
<thead><tr><th>Item</th><th>Price</th></tr></thead>
<tbody>
<?php for ($x = 1; $x <= $count; $x++) { ?>
<tr><?php echo $metadata; ?></tr>
<?php } ?>
</tbody>
</table>
Which is doing this:
Im getting close!
<?php
$sql="
SELECT * FROM table WHERE pid=".$this->item->id."
AND
meta_id IN (SELECT meta_id FROM table GROUP BY meta_id HAVING COUNT(*) > 1)
";
$db->setQuery($sql);
$meta= $db->loadObjectlist();
foreach($meta as $data){
$metadata .= '<tr><td>'.$data->meta_data.'</td></tr>';
}
?>
<table class="table table-striped">
<thead><tr><th>Item</th><th>Price</th></tr></thead>
<tbody>
<?php echo $metadata; ?>
</tbody>
</table>
The above is now giving me this:

$sql="SELECT "put here column name you want to display in html table "
FROM table WHERE pid=".$this->item->id." ORDER BY meta_data ASC";
for example : if you column name(s) are Item & price than query look like
$sql="SELECT Item,price FROM table WHERE pid=".$this->item->id."
ORDER BY meta_data ASC";
so you get only item & price from database.
another approach is you can make some changes in your loop like,
foreach($meta as $data){
$metadata .= '<td>'.$data->meta_data['Item'].'</td>
<td>'.$data->meta_data['Item'].'<td>';
}

Related

php table <th> and <td> from Database Selected but they are not Matching in the right indexing position

all Developers.
I am developing School Management System, in the Database, I have two tables one is For Subjects, and the other one is designed for obtained marks of the Subjects and it is called scores.
So I am trying to fetch subject Names as Table Head
I have another Query below this query and I am trying to fetch from scores as table data .
At this point, I failed to match the subject name and its score from the scores table.
Here is my code:
<table class="table table-striped table-bordered">
<head>
<tr>
<?php
// Query for Subject Names
$view_subject = $config->prepare("SELECT * FROM subjects");
$view_subject->execute();
while($row = $view_subject->fetch()){
$sub_name = htmlspecialchars($row['sub_name']);
?>
<th class="text-center"style="background-color:#395C7F;color:#fff;"><?php echo $sub_name;?></th>
<?php } ?>
</tr>
</thead>
<body>
<?php
// Query for Subject Scores
$view_scores = $config->prepare("SELECT * FROM scores INNER JOIN subjects ON scores.score_sub_id = subjects.sub_id WHERE scores.std_rand = :random_id ORDER BY scores.score_sub_id ASC");
$view_scores->execute(['random_id' => $rand_ID]);
while($row = $view_scores->fetch()){
$score_id = htmlspecialchars($row['score_id']);
$score_sub_id = htmlspecialchars($row['score_sub_id']);
$score_mid_amount = htmlspecialchars($row['score_mid_amount']);
$score_final_amount = htmlspecialchars($row['score_final_amount']);
?>
<tr>
<td class="text-black" data-title="Subject"><?php echo $score_mid_amount;?></td>
</tr>
<?php } ?>
</tbody>
</table>
Database images:
1- Subjects table
2- Scores table
** Browser UI **
On your second loop you have entered '<tr>' wrapping each '<td>' that means that each one arrives at a different line , '<td>'s should be as much as there are '<th>' for each line.... so :
<?php
// Query for Subject Scores
$view_scores = $config->prepare("SELECT * FROM scores INNER JOIN subjects ON scores.score_sub_id = subjects.sub_id WHERE scores.std_rand = :random_id ORDER BY scores.score_sub_id ASC");
$view_scores->execute(['random_id' => $rand_ID]);
?>
<tr>
<?php
while($row = $view_scores->fetch()){
$score_id = htmlspecialchars($row['score_id']);
$score_sub_id = htmlspecialchars($row['score_sub_id']);
$score_mid_amount = htmlspecialchars($row['score_mid_amount']);
$score_final_amount = htmlspecialchars($row['score_final_amount']);
?>
<td class="text-black" data-title="Subject"><?php echo $score_mid_amount;?></td>
<?php } ?>
</tr>
</tbody>
</table>
This should fix your table but it will only create one line! if you have more than one line you will need to add another loop to wrap this one and it will create the new '<tr>' outside the inner loop.
BTW: I assume that the 2nd while loop is exactly long as the first one... since you are supposed to have the same amount of <td> per line per <th> if it's not in the same length or not sorted the same way you will have an issue... which can be resolved either by adjusting your SELECT or creating an array with ids and injecting to it the data from the second loop according to the keys brought in the first.

How do I add another mysqli query into a while loop?

So I am carrying out a query and returning the results in the form of a table. The code below works well.
<table>
<thead>
<tr style="text-align: center;">
<th>Activity</th>
<th>Description</th>
<th>Frequency</th>
<th>Mandatory</th>
<th>Added Yet</th>
</tr>
</thead>
<tbody>
<?php
$stmt = $conn->prepare("SELECT * FROM knowledgebase ORDER BY category ASC");
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) echo "<tr><td>No activities found</td><td></td><td></td><td></td><td></td><td></td></tr> </tbody>
</table></br></br>
Why not add your first activity from our Knowledge base or create a new activity of your own";
else {
while($row = mysqli_fetch_array($result)) {
$activity_id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$frequency = $row['frequency'];
$mandatory = $row['mandatory'];
echo "<tr><td>".$title."</td><td>".$description."</td><td style=\"text-align: center;\">".$frequency."</td><td style=\"text-align: center;\">".$mandatory."</td><td></td></tr>";
}
}
$stmt->close();
?>
</tbody>
</table>
What I want to add in is another query inside the final <td></td>. What I want to do is query a second db table and say if this activity has already been added to the users table, echo YES, otherwise, echo NO.
The problems is, adding the query into the while loop keeps throwing errors.
Any suggestions gratefully received.
Instead of running another query for every row, you could join the users table to the knowledgebase table in your first query. If you use a left join, you'll still get all the rows from knowledgebase.
SELECT knowledgebase.*, userstable.activity_id
FROM knowledgebase
LEFT JOIN userstable ON knowledgebase.id = userstable.activity_id
ORDER BY category ASC
Then in your last <td>, you can print YES/NO depending on whether or not there was a matching row in the users table.
...<td><?php echo $row['activity_id'] ? 'YES' : 'NO' ?></td>...
(I made up names for your other table and column, but I think it shows the general idea.)

Fetching rows from database and making them links to other pages

I think the question title is not so accurate but here are the details of the problem i am facing.
I have Movies Database in Oracle10g
I have included an option for user to search for movies in the database by title.
I am using this piece of code to Display the rows Retured...
<h1>Search Results</h1>
<table border = "1px">
<thead>
<tr>
<th>ID</th>
<th>RATING</th>
<th>Title</th>
<th>Description</th>
<th>Category</th>
<td>Duration</td>
<td>Actor</td>
</tr>
</thead>
<tbody>
<?php
$search = $_POST['search'];
$search = sanitize($search);
$search = '%'.$search.'%';
$conn = oci_connect("asim","asim","localhost/xe");
$stid = oci_parse($conn,"SELECT
film.film_id AS FID,
film.title AS title,
film.description AS description,
category.name AS category,
film.duration AS length,
film.rating AS rating,
CONCAT ( actor.first_name ,CONCAT(' ', actor.last_name)) AS actors
FROM category
LEFT JOIN film_category ON category.category_id = film_category.category_id
LEFT JOIN film ON film_category.film_id = film.film_id
JOIN film_actor ON film.film_id = film_actor.film_id
JOIN actor ON film_actor.actor_id = actor.actor_id
WHERE title LIKE '".$search."'");
oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
print "<tr>\n";
foreach ($row as $item) {
print " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
print "</tr>\n";
}
?>
</tbody>
</table>
I am getting the results Displayed in a table form!
now what i want is that make the title or the film_id of every film fetched to be a link.
and when clicked it should navigate to a specific page of that Movie.
That page could be like index.php?id=1337
and on the index page $_GET['userid'] could be used to fetch info about that movie
The main problem is making the film_id or title or the whole row a link
I tried using the tag but wasnt successful.
I am a newbie to PHP and oracle.
Any kind of help would be very appreciated.
If you check out the documentation for oci_fetch_array found here you will see that because you are using OCI_ASSOC parameter you are able to access the results using their named keys.
Inside you while loop you should be able to access the film_id using the column name you specified in the Oracle SELECT query, FID.
$row['FID']
You can then generate a link to that using the html anchor tag <a>.
print 'link text';
Something similar to this is tying it all together, I have an example you can try below that will show you how to access the data as mentioned above, you should be able to continue from there.
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
print $row['PID'] . '<br />';
}

Display MySQL table ( number of rows are not same ) in PHP

I have one MySQL table and it has two columns -
I want to display in my site like this -
I can easily take the table name Boy | Girl . But when i try to display the table I get like this -
I am just showing one example here. There may be 50 boys and 10 girls.. So I need help.
After displaying the heading
while($row_type = mysql_fetch_array($type))
{
$type_name = $row_type['type_name']; //Boy (or) Girl taking from another table
$type_name = Database::getInstance()->query("SELECT * FROM details WHERE type='type_name'");
echo "<tr>";
while($row_name = mysql_fetch_array($type_name))
{
echo "<td>$row_name[type_name]</td>"; //Displaying the names
}
echo "</tr>";
}
So many views but not getting any answer. Please help guys. Please catch my mistake.
Try with two queries.
Make an array for each category(Male & Female)
It Works.
$maleQuery = mysql_query("SELECT * FROM table WHERE category='male'");
$femaleQuery = mysql_query("SELECT * FROM table WHERE category='female'");
while(($row = mysql_fetch_assoc($maleQuery))) {
$males[] = $row['name'];
}
while(($row = mysql_fetch_assoc($femaleQuery))) {
$females[] = $row['name'];
}
$number_of_rows = max(sizeof($males),sizeof($females));
echo "<table border='1'>";
echo "<tr><td>Male</td><td>Female</td></tr>";
for($i=0;$i<$number_of_rows;$i++)
{
echo "<tr><td>".#$males[$i]."</td><td>".#$females[$i]."</td></tr>";
}
Try this query 100% working but set php code.
SELECT IFNULL(c.Boy,'')AS Boy,IFNULL(c.Girl,'')AS Girl FROM
(SELECT x.name,CASE WHEN (x.category = 'boy') THEN x.name END AS Boy,CASE WHEN (x.category = 'girl') THEN x.name END AS Girl FROM (SELECT * FROM tablename) X)c
Is your problem to do with the creation of the table using PHP or is it related to the SQL query itself?
If it is the creation of the table then I suggest you use two tables embedded in a single table like this. That way you can build the first table using one SQL query, then build the second table using a second query, then display the table and girls and boys will appear side by side regardless of how many entries on each side. Your code would look a bit like this:
echo "<table>
<tr>
<td>
<table>
<tr><th>Boy</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Boy'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
<td>
<table>
<tr><th>Girl</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Girl'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
</tr>
</table>";
If you need to cater for more categories, do an initial search to determine the distinct categories, then put the section of code above that creates the inner table in a loop.
eg. in pseudo code:
echo the outer table <table><tr>
SELECT DISTINCT Category FROM details
while row1=get next category
$cat = row1[0];
echo "<td>
<table>
<tr><th>".$cat."</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = '".$cat."'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
echo the </tr></table> to close the outer table

Preventing dynamic PHP table display correctly

I have the following code to display a block of six products from a mysql database.
It displays as two columns three rows and I get individual photos and correct page links in each of the six positions but the alt tags for the three products in column one are repeated in column 2. I cannot work out why. Any thoughts, and ways to improve the code?
<?php
// create query
$query = "SELECT * FROM photogear WHERE qty != 0 ORDER BY id DESC LIMIT 6";
// execute query
$result = mysql_query($query) or die(MYSQL_ERROR);
?>
<table>
<?php
while($row = mysql_fetch_array($result)){
$product2=$row['product'];
$img2=$row['img'];
$manuid2=$row['manuid'];
$id2=$row['id'];
$price=$row['price'];
//GET MANUFACTURER FOR DISPLAY IN img title
$manu_q = "SELECT * FROM manufacturers WHERE manuid = '$manuid2' ORDER BY name";
$manu_r = mysql_query($manu_q) or die(mysql_error());
$manu_info = mysql_fetch_array($manu_r);
$name2=$manu_info['name'];
?>
<tr>
<td>
<?php // for each product show photo with a link to product page
echo "<a href='product-".$row['id']."'><img src='".$row['img']."'alt='$name2,$product2 $price' title='$name2 $product2 £$price' width='85'></a>";
?>
<?php $row=mysql_fetch_assoc($result); // make one record out.?>
</td>
<td>
<?php // for each product show photo with a link to product page
echo "<a href='product-".$row['id']."'><img src='".$row['img']."' alt='$name2, $product2 $price' title='$name2 $product2 £$price' width='85'></a>";?>
</td>
</tr>
<?php
} // End loops.
?>
</table>
Any help much appreciated
Instead of using $product2, $price try using $row['product'],$row['price'] in alt
Just try this but im not sure
Use this
SELECT * FROM manufacturers WHERE manuid = '$row['manuid']' ORDER BY name
Instead of this
SELECT * FROM manufacturers WHERE manuid = '$manuid2' ORDER BY name
After this
$row=mysql_fetch_assoc($result);
Add this line
$manu_info = mysql_fetch_assoc($manu_r);

Categories