matching data in two tables if match..Display the Name and msg - php

I have two tables in mysql. Following is my script.
<?php
$conn=mysql_connect("localhost",'root','');
mysql_select_db('test');
$sql = "SELECT data_student.name,ozekimessagein.msg
FROM ozekimessagein,data_student
WHERE ozekimessagein.sender=data_student.sender
ORDER BY ozekimessagein.msg";
$res=mysql_query($sql);
$cn=mysql_num_rows($res);
for($x=0;$x<$cn;$x++)
{
list($name,$msg)=mysql_fetch_row($res);
echo "<li>$name,$msg";
}
mysql_close($conn);
?>
this should display the name from table data_student table and the message from ozekimessagein as long as the sender in data_student table match with the sender in the ozekimessagein table. But it doesn't work.

Try this ::
SELECT
data_student.name,
ozekimessagein.msg
FROM ozekimessagein
inner join data_student on ozekimessagein.sender=data_student.sender
ORDER BY ozekimessagein.msg

try this
<?php
$conn=mysql_connect('localhost','root','');
mysql_select_db('test');
$sql = "
SELECT s.name AS names, o.msg AS msgs
FROM ozekimessagein o
INNER JOIN data_student s
ON o.sender = s.sender
ORDER BY s.name";
$res=mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
echo "<li>".$row['names']." : ".$row['msgs']."</li>";
}
mysql_close($conn);
?>

Related

Select distinct in SQL?

The select distinct not working and the count(*) is not selecting the number of grouped rows but it is selecting the duplicate msg_contents.Please help..
I wanted to select distinct username and the number of duplicate usernames.
<?php
require_once"cnc.php";
$sort = "SELECT hate_p FROM hate_t";
$qry = mysql_query($sort);
while($fet = mysql_fetch_assoc($qry)) {
if($fet == 0) {
echo "No Entries";
} else {
$sql = mysql_query("
SELECT DISTINCT
username,
msg_content,
COUNT(*) c
FROM messages
WHERE msg_content LIKE '%".$fet['hate_p']."%'
GROUP BY username HAVING c>0"
);
while($messages = mysql_fetch_assoc($sql)) {
?>
<tr>
<td><?php echo $messages['username'];?></td>
<td><?php echo $messages['c'];?></td>
</tr>
<?php
}
}
}
?>
you don't need distinct in this case, you can use group by only, distinct get all rows with distinct all columns you select (username,meg_content,count):
SELECT username,msg_content,COUNT(*) c
FROM messages WHERE msg_content LIKE '%".$fet['hate_p']."%'
GROUP BY username,msg_content
HAVING c>0
remove msg_content from distinct? you already have it. and #gouda is right, you probably don't need the distinct at all.

Displaying name from an inner joined table?

I've got two tables, one called category, which has the rows id and name, and another called placecategory, which has the tables id, place_id and category_id. I need to inner join these two to echo out the names of the categories where the placecategory.place_id is equal to a $GET[ID].
I've got this so far, but it echo's out nothing.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name FROM category
INNER JOIN placecategory
ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id.'';
$result = mysqli_query($dbc,$qry);
while ($row = mysqli_fetch_array($result))
{
echo ''.$row['name'].'';
};
?>
This wont fix your query, but it will display the error generated by the incorrect query. Its a start.
I cannot solve the query issue without a better understanding of your schema.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name
FROM category
INNER JOIN placecategory ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id;
$result = mysqli_query($dbc,$qry);
// test the status before continuing
if ( ! $result ) {
echo mysqli_error($dbc);
exit;
}
while ($row = mysqli_fetch_array($result))
{
echo $row['name'];
}
?>

Echo rows via JOIN in MySQL/PHP (?)

I wanna be able to echo out if Groupname and Username are connected correctly, where the current userid (saved in a session) is $uid.
I've been sitting for hours trying all kinds of JOINs and the closest I've gotten is having it output 1/? members for each team, but not all of them.
EDIT:
$uid = $_SESSION['uid'];
$sql = "SELECT * FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user
INNER JOIN usergroup ON user.userid=usergroup.userid
WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
$row2 = mysqli_fetch_array($result2);
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
Thing is, that it kinda works well, except that it doesn't print all the groupmembers names out, it prints out just one. Which one seems to depend on the order in the table.
You did not have a loop on the second query's resultset. However, it is not needed to have a second SQL query. Just do it in one go; SQL was designed for that.
Also, you'll have much simpler code:
$uid = $_SESSION['uid'];
// Select everything you need in one go (join user table as well)
$sql = "SELECT group.group_id, group.groupname, user.username
FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
INNER JOIN user ON user.userid=usergroup.userid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
// Don't need to call mysqli_num_rows if you continue like this:
while($row = mysqli_fetch_array($result)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
Maybe you want to echo some <tr> and </tr> tags, or you"ll have everything in one row, like:
echo "<tr><td>".$row['groupname']."</td>"
."<td>".$row['username']."</td>"
."<td>".$row['groupid']."</td></tr>";
There you go: (you were missing nested while loop)
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user INNER JOIN usergroup ON user.userid=usergroup.userid WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
if(mysqli_num_rows($result2)>0) {
while($row2 = mysqli_fetch_array($result2)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
}
}
Side note: You could achieve the same results with just one SQL query, something like:
SELECT
*
FROM
usergroup ug
INNER JOIN
user u ON ug.userid = u.userid
GROUP BY
ug.id
and then in PHP (pseudo code just, do not copy-n-paste)
while($row => mysqli_fetch_array($result)) {
if (!isset($groupsWithUsers[$row['groupid']['users'])) {
$groupsWithUsers[$row['groupid']['users'] = array()
}
$groupsWithUsers[$row['groupid']['users'][$row['userid']] = $row;
}

Getting string value instead of foreign id in a one to many relationship

I have a query that will display the fields/values of a table that is related to other table.Using foreach loop, I can display those fields/values in html.But I want to display the the 'foreign_name' instead of 'foreign_id'.
<?php foreach ($table_related as $table): ?>
<?php echo $table['id']; ?>
<?php echo $table['foreign_id']; ?>//the foreign key, it should be foreign_name
<?php echo $table['name'];?>
<?php endforeach; ?>
//classeManageService.php
function showAllServices()
{
$query = $this->link->query("SELECT * FROM services ORDER BY id DESC");
$rowcount = $query->rowCount();
if($rowcount > 0)
{
$result = $query->fetchAll();
return $result;
}
else
{
return $rowcount;
}
return $result;
}
//show_all.php
<?php
include_once('../../classes/class.ManageServices.php');
$init = new ManageServices();
$show_all_services = $init->showAllServices();
?>
'my_table' has columns id,my_name,desc,foreign_id and 'other_table' has columns foreign_id,foreign_name,foreign_desc
I can display all those values in html.But how about displaying the other fields instead of its id from the other table?Do I have to change my query?Any Ideas?
You have to do a query with a JOIN:
Since you didn't provide the other table name, please consider otherTable as it, and service_id as foreign key.
Query example:
$query = $this->link->query("SELECT * FROM services s, otherTable o WHERE s.id = o.service_id ORDER BY s.id DESC");
now in the result set you will have also all the fields of otherTable from which you will be able to get the name as desired.
ok I got it, I change my query
From
$query = $this->link->query("SELECT * FROM services ORDER BY id DESC");
into
$query = $this->link->query("SELECT services.*, services_type.name FROM services JOIN services_type USING(services_id)") ;
Now its working, Yayy..

Get result of mysql_query inside while of mysql_fetch_array

I am using a code something like below to get data from the second table by matching the id of first table. Code is working well, but I know it slow down the performance, I am a new bee. Please help me to do the same by an easy and correct way.
<?php
$result1 = mysql_query("SELECT * FROM table1 ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ))
{
$tab1_id = $row1['tab1_id'];
echo $row['tab1_col1'] . "-";
$result2 = mysql_query("SELECT * FROM table2 WHERE tab2_col1='$tab1_id' ") or die(mysql_error());
while( $row2 = mysql_fetch_array( $result2 ))
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
}
?>
You can join the two tables and process the result in a single loop. You will need some extra logic to check if the id of table1 changes, because you'll only want to output this value when there's a different id:
<?php
// Join the tables and make sure to order by the id of table1.
$result1 = mysql_query("
SELECT
*
FROM
table1 t1
LEFT JOIN table2 t2 ON t2.col1 = t1.id
ORDER BY
t1.id") or die(mysql_error());
// A variable to remember the previous id on each iteration.
$previous_tab1_id = null;
while($row = mysql_fetch_array( $result1 ))
{
$tab1_id = $row['tab1_id'];
// Only output the 'header' if there is a different id for table1.
if ($tab1_id !== $previous_tab1_id)
{
$previous_tab1_id = $tab1_id;
echo $row['tab1_col1'] . "-";
}
// Only output details if there are details. There will still be a record
// for table1 if there are no details in table2, because of the LEFT JOIN
// If you don't want that, you can use INNER JOIN instead, and you won't need
// the 'if' below.
if ($row['tab2_col1'] !== null) {
echo $row['tab2_col2'] . "-";
echo $row['tab2_col3'] . "</br>";
}
}
Instead of having 2 while loops, what you can do is join the 2 tables and then iterate over the result.
If you're not sure what join is look here: https://dev.mysql.com/doc/refman/5.1/de/join.html
Also here is a fairly simple query written using join: Join Query Example
You can use this. One relation with two tables:
<?php
$result1 = mysql_query("SELECT tab2_col2, tab2_col3 FROM table1, table2 where tab2_col1 = tab1_id ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ),)
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
?>
Like Sushant said, it would be better to use one JOIN or simpler something like that:
SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id

Categories