PHP MySQL join two tables query - php

I have two tables ie abstract table and author with one to many relation, for each iteration on while loop I want to display a html table of unique row of data from abstract table with corresponding rows from author table.
This what I did:
public function getAll() {
try {
$sql = " SELECT tbl_abstract.abstract_id, tbl_abstract.first_name,
tbl_abstract.last_name,tbl_abstract.content,
tbl_author.afirst_name, tbl_author.alast_name,
tbl_author.aaffilition
FROM tbl_abstract
INNER JOIN tbl_author ON tbl_abstract.abstract_id = tbl_author.abstract_id
GROUP BY tbl_abstract.abstract_id";
$stmt= $this->pdo->prepare($sql);
$stmt->execute();
$count = $stmt ->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
<table class="table" >
<tr>
<td align="center" >
//data from tbl_abstract
<?php echo $row["abstract_id"]; ?>. <?php print($row["abstract_title"]); ?>
<?php echo $row["first_name"].' '.$row["last_name"]; ?>,
//data from tbl_author
<?php echo $row["afirst_name"].' '.$row["alast_name"];?>
</td>
</tr>
<tr>
<td align="center" ">
//data from tbl_abstract
<?php print($row["content"]); ?>
</td>
</tr>
</table>
<?php
}
}catch(PDOException $e){
echo $e->getMessage();
return false;
}
}
There are three records from tbl_author associated with the abstract_id from tbl_abstract but i only get one record instead of 3 of them.Please help

Try this one :-
<?php
$sql = "SELECT *
FROM tbl_abstract
where abstract_id IN (SELECT distinct abstract_id
FROM tbl_abstract)";
$stmt= $this->pdo->prepare($sql);
$stmt->execute();
$count = $stmt ->rowCount();
?>
<table class="table" >
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td align="center" >
//data from tbl_abstract
<?php echo $row["abstract_id"]; ?> <?php print($row["abstract_title"]); ?>
<?php echo $row["first_name"].' '.$row["last_name"]; ?>,
<?php
$sql1 = "SELECT *
FROM tbl_author
WHERE abstract_id = '".$row["abstract_id"]."'" ;
$stmt1= $this->pdo->prepare($sql1);
$stmt1->execute();
while($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)){
//data from tbl_author
echo $row1["afirst_name"].' '.$row1["alast_name"];
} ?>
</td>
<td align="center">
//data from tbl_abstract
<?php print($row["content"]); ?>
</td>
</tr>
<?php } ?>
</table>

Try removing the GROUP BY clause like this:
SELECT
tbl_abstract.abstract_id, tbl_abstract.first_name,
tbl_abstract.last_name,tbl_abstract.content, tbl_author.afirst_name,
tbl_author.alast_name, tbl_author.aaffilition
FROM
tbl_abstract
INNER JOIN
tbl_author ON tbl_abstract.abstract_id = tbl_author.abstract_id
Group by is grouping all the authors by the field abstract_id, which means, that it won't return all the authors, but only one for one abstract_id (based on the sorting field, which in this case is probably the primary key, because it is not explicitly defined)..

Related

php // what should i do to display all courses?

i need to display all courses at once
in my code only display one course what should i do to fix it ?
when i click delete it reload page and display next courses
my code ::
$course = $conn->query("select * from student_course where student_id = $id ") ;
if($course->num_rows > 0) {
?>
<table class="table" >
<tr>
<thead>
<th> courseName </th>
<th> courseID </th>
<th> teacher </th>
<th> DELETE </th>
</thead> </tr>
<?php
while ($Scourse = $course->fetch_assoc()){
$cid=$Scourse['course_id'];
$tid=$Scourse['teacher_id'];
$teacher = $conn->query("select * from teacher where id = $tid ") ;
if($teacher->num_rows > 0) {
while($teacherC=$teacher->fetch_assoc()){
$course = $conn->query("select * from course where id = '$cid' ") ;
if($course->num_rows>0){
while($Ncourse=$course->fetch_assoc()){ ;
?>
<tr> <td><?php echo $Ncourse['name']; ?> </td>
<td><?php echo $Scourse['course_id']; ?> </td>
<td> <?php echo $teacherC['name']; ?> </td>
<td><form method="post"><button type="submit" name="<?php echo $cid ?>"> Delete </button></form> </td></tr>
<?PHP
if (isset($_POST["$cid"])){
$dcourse = $conn->query("delete from student_course where course_id = '$cid' and
student_id=$id ") ;
header("location:scourse.php");
}
}
}
}
}
}
}
</table>
i try to delete teacher and course query it work as i need
You're handling associate arrays improperly.
You will need a foreach loop to loop through each row in the associate array.
Example:
foreach($Scourse as $x) {
echo $x['name'];
echo $x['course_id'];
}
See Loop through Associate Arrays here:
https://www.w3schools.com/php/php_arrays.asp
Edit: See #Qirel comments

how to fetch colums data from two table using mysql with php using where

I have two Table ownership_profile and socity_unit.
Query For table1: select * from ownership_profile where SID='$id'
Query For Table2: select * from socity_unit where socity_id='$sid'
I have to join with one query, but i don't have idea how to do it.
This is my Php code but gives error:
<!-----------------Table For User Names-------------------------------------->
<table border="1" align="center">
<tr>
<th>Unit No</th>
<th>Member Name</th>
<th>Wing</th>
<th>Unit</th>
</tr>
<?php
if(isset($_GET['submit']))
{
$sql = "select * from ownership_profile o inner join society_unit s on o.sid = s.society_id where o.sid = '$sid' ";
$result = mysql_query($sql);
$i=1;
while($row=mysql_fetch_array($result)){
?>
<?php
$name = $row['NAME'];
$unitid = $row['UNIT_ID'];
$sid = $row['SID'];
$wings = $row['wings'];
$unit_no = $row['unit_no'];
{
?>
<!--User Submit Result-->
<tr>
<td><?php echo $unitid; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $wings; ?></td>
<td><?php echo $unit_no; ?></td>
</tr>
<?php }?>
<?php
//echo "<br>";
$i++;
}
}
?>
inner join is what you want.
select *
from ownership_profile o
inner join society_unit s
on o.sid = s.society_id
where o.sid = '$sid'
This assumes that 'sid' and 'society_id' are the relationship identifiers.
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
select * from ownership_profile o inner join socity_unit s on o.SID = s.socity_id where o.SID = '$SOCIETY_ID'
This query working fine but...... its generate dublicate entry from table

Merging data into one column mysql using php

good day i am building a website for recipes and im trying to display a recipe with multiple ingredients but the ingredients are in a separate table so when i run the query if i have three ingredients the recipe id will appear three times along with the other data because the ingredients column is populated by only one entry...is there anyway to merge these entries?
here is my code and link to an image of how the data is appearing..any help would be great
[img]http://forums.trinituner.com/upload/data/62/all recipes duplicate.jpg[/img]
my code
$db=mysql_select_db("tasteofhome");
$query = "select RECIPES.recipe_ID,RECIPES.recipe_name,RECIPES.recipe_author,RECIPES.cook_time,RECIPES.stages_description, INGREDIENTS.ingredients_name, USERS.user_name from
RECIPES,USERS,RECIPE_INGREDIENTS,INGREDIENTS where USERS.user_ID=RECIPES.user_ID AND
RECIPES.recipe_ID = RECIPE_INGREDIENTS.recipe_ID
AND RECIPE_INGREDIENTS.ingredients_ID = INGREDIENTS.ingredients_ID
";
$result = mysql_query ($query);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while ($rows = mysql_fetch_array ($result))
{ //begin of while loop
?>
<tr>
<td> <?php echo $rows [0]; ?> </td>
<td> <?php echo $rows [1]; ?> </td>
<td> <?php echo $rows [2]; ?> </td>
<td> <?php echo $rows [3]; ?> </td>
<td> <?php echo $rows [4]; ?> </td>
<td> <?php echo $rows [5]; ?> </td>
<td> <?php echo $rows [6]; ?> </td>
</tr>
<?php
} //end of while loop
?>
You could join the recipes and users tables with an aggregate query that uses group_concat to join the ingrediants to a coma-delimited string:
SELECT r.recipe_ID,
r.recipe_name,
r.recipe_author,
r.cook_time,
r.stages_description,
gi.ingredients_names,
u.user_name
FROM RECIPES r
JOIN USERS u ON u.user_ID = r.user_ID
JOIN (SELECT ri.recipe_ID,
GROUP_CONCAT(i.ingredients_name) AS ingredients_names
FROM RECIPE_INGREDIENTS ri
JOIN INGREDIENTS i ON ri.ingredients_ID = i.ingredients_ID
GROUP BY recipe_ID) gi ON gi.recipe_ID = r.recipe_ID

How to show comments under a post like facebook does?

I'm trying to make a facebook wall-alike php script.
It loads the posts stuff, photo url and user stuff like username and user id from my MySQL database. It also checks if the post is just a comment to another post (parentof). I can present all the original posts with pictures with a simple do-while using tags .
But how could I present the comments under every post? I guess with another do-loop, but how?
Here is my code:
<?php
require_once "config.php";
$result = mysql_query('SET NAMES utf8');
$result = mysql_query('SET CHARACTER SET utf8');
$wallhaku = mysql_query("SELECT `wall`.`post_id`, `wall`.`parentof`, `wall`.`sentby`, `wall`.`text`, `wall`.`image_url`, `users`.`username`, `users`.`photopath`, `users`.`name`, `users`.`member_id` FROM `wall` LEFT JOIN `users` ON `wall`.`sentby` = `users`.`member_id` WHERE parentof=0 ORDER BY post_id DESC") or die (mysql_error());
$row_wallhaku = mysql_fetch_array($wallhaku);
<table width="800" height="120" border="0" cellpadding="10">
<?php $i=0; $numberpage=1;
do {
$wallid = $row_wallhaku['post_id'];
$parenthaku = mysql_query("SELECT post_id, parentof FROM wall WHERE parentof=$wallid") or die (mysql_error());
$row_parenthaku = mysql_num_rows($parenthaku);
<td width="120" align="left">
<img src=<?php echo $row_wallhaku['photopath']; ?> height= "100" width="100">
</td>
<td width="600" align="left">
<?php echo $row_wallhaku['name']?><br /><p><?php echo $row_wallhaku['text'];
if($row_wallhaku['image_url']=="0") {
<p align="right"><?php echo $row_parenthaku ?> kommenttia. Lue, kommentoi <?php } ?></td>
<?php $i++; if($i%$numberpage==0) echo "</tr>";
if($row_wallhaku['image_url']!="0")
{
<tr>
<td width='800' colspan='2' align='center'>
<img src=<?php echo $row_wallhaku['image_url']; ?> height="180">
<p align="right"><?php echo $row_parenthaku ?> kommenttia. Lue, kommentoi
</td>
</tr>
<?php
}
</table>
In case that the relation between posts is one to many , You need to use 2 queries.
The first query will get the data of the topic (the post).
The other query will get the data of all the comments which "parentof" equals the topic's id.
$id = $_GET['id'];
$getTopic = mysql_query("SELECT * FROM posts WHERE id='$id'");
$topic = mysql_fetch_array($getTopic);
$getComments = mysql_query("SELECT * FROM posts WHERE parentOf='{$topic['id']}'");
while($comment = mysql_fetch_array($getComments))
{
echo $comment['title']; //You should use a "view" functin which handles the HTML and staff.
}

Got stuck with populating mysql table in html table [duplicate]

Here the value of $table will be passed from another file and it will be a table name in a database.
With that table name ($table) am trying to fetch its column names and all the values in the table and make the table look like an actual one we see in phpMyAdmin.
As a result of the code below. I can only get the column names. But not the data. Please tell me what should i do to perform the task of showing the datas in the table
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="display" rel="datatable">
<thead>
<tr>
<?php
//echo"select * from $table";
$qq=mysql_query("show columns from $table");
if(mysql_num_rows($qq)>0){
//$i=1;
echo '<tr>';
while($rs = mysql_fetch_row($qq))
{
$sel=mysql_query("select * from $table");
$fetch=mysql_fetch_object($sel);
//while($fetch=mysql_fetch_object($sel))
//{
?>
<td><?php echo $fetch->$rs[0];?></td>
<?php
//}
//$i++;
}
echo '</tr>';
}
else
{
?>
<tr>
<td colspan="11">No data to display</td>
</tr>
<?php
}
?>
</tbody>
</table>
Yes only columns will be printing because you are printing $rs[0];?> where $rs holds object for mysql_query qq and it holds your column query only not
"select * from $table"
this.
Why dont you try displaying columns as a single row in html table and then try displaying data from other php set with seperate query structure .
Hope this way it helps.
I coudn't fix your code because it was getting ugly, so i remade it:
php:
function mysql_fetch_all($res) {
$result = array();
while ($row = mysql_fetch_row($res)) {
$result[] = $row;
}
return $result;
}
function getColumnsAndData($table) {
$table = mysql_real_escape_string($table);
$q1 = mysql_query("show columns from $table");
$q2 = mysql_query("select * from $table");
return array(mysql_fetch_all($q1), mysql_fetch_all($q2));
}
list($columns, $data) = getColumnsAndData($table);
?>
html
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="display" rel="datatable">
<thead>
<tr>
<?php foreach ($columns as $column): ?>
<td><?php echo $column[0] . ' ' . $column[1] ?></td>
<?php endforeach; ?>
<tr>
</thead>
<tbody>
<?php if (count($data) > 0): ?>
<?php foreach ($data as $row): ?>
<tr>
<?php foreach ($row as $value): ?>
<td><?php echo $value ?></td>
<?php endforeach; ?>
<tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td>No data to display</td>
</tr>
<?php endif; ?>
</tbody>
</table>

Categories