Reading data from two tables on a same database, using "if - else" - php

ok guys I need a bit of help with this, remaking this to format ir properly.
I have this code:
(this is accessing a table called "students" in database.)
<?php
require_once('connection.php');
$id = $_SESSION['SESS_MEMBER_ID'];
$result3 = mysql_query("SET NAMES UTF8;");
$result3 = mysql_query("SELECT * FROM students where mem_id='$id'");
while($row3 = mysql_fetch_array($result3))
{
$fname = $row3['fname'];
$country = $row3['country'];
$class = $row3['class'];
$headteacher = $row3['headteacher'];
$attendance = $row3['attendance'];
$homework = $row3['homework'];
$messagestudent = $row3['messagestudent'];
}
?>
<?php
if($class=='K1')
echo "teacher 1";
else if($class=='K2')
echo "teacher 2";
else if($class=='K3')
echo "teacher 3";
?>
In another table, i have the teacher names and what i need to do and i cannot find the right way to do it, is to call the teacher's name from the table "teachers" after the query confirms the K1, K2 or K3 data on the "students" table column "class".
Basically what i need is to change the contents of the echo part, switching it from static data needed to be within the code, to a data contained on another table, for example. both tables have a column called "class", so if class column for a student says "K1" i want this to then go check the "teacher" table's column "class" and pick the one that matches "K1" and display it in the result echo, I'm sure it is possible, but not with my current skill level.
The table structure for students is:
mem_id, username, password, fname, country, class, attendance, homework, messagestudent
The table structure for teacher is:
mem_id, class, name, comment
Hope you guys shed some light on me!
Thanks in advance.
PS. I know the query is using the deprecated mysql_, but when I tried to change it to mysqli_ following a guide, it never worked.

If I understood, you can get the desired data through this query (without JOIN or if statement):
SELECT students.*,teachers.name FROM students,teachers WHERE students.id='$id' AND students.class = teachers.class
It returns the teacher name according the student class, at the same row.

You can use left join for this. Try using following query:
SELECT * FROM students as st
LEFT JOIN teachers AS ts
on st.class=ts.class
WHERE st.mem_id = '$id'
You don't need to use if-else statement for this. And it will also work with mysqli.
According to your script, it should work like:
<?php
require_once('connection.php');
$id = $_SESSION['SESS_MEMBER_ID'];
$result3 = mysql_query("SET NAMES UTF8;");
$result3 = mysql_query("SELECT st.*, ts.name AS teacher_name FROM students as st LEFT JOIN teachers AS ts on st.class=ts.class WHERE st.mem_id = ".$id);
while($row3 = mysql_fetch_array($result3))
{
$fname = $row3['fname'];
$country = $row3['country'];
$class = $row3['class'];
$headteacher = $row3['headteacher'];
$attendance = $row3['attendance'];
$homework = $row3['homework'];
$messagestudent = $row3['messagestudent'];
$teachername = $row3['teacher_name'];
}
echo $class. ' - '. $teachername;
?>

Related

Current selection does not contain a unique column. Mysqli. Duplication?

I can't seem to select/retrieve the "Package Table" and merge it into 1 table that contains the other table which is "Events Table". I don't know what seems to be the problem though.
Whenever i tried to execute my query and the only thing that pops up is the
events_ table, the Package table on the other hand does not. I tried another another simple query,
SELECT * FROM event_table JOIN package ON event_id WHERE cusact_id = 8 AND event_id=80
And the query works fine.
Event Table (Structure):
http://prntscr.com/gbr6vr
Package Table (Structure):
https://prnt.sc/gbr793
Note: I have a column named package_id on events_table and package. Is that the problem? Im sorry, still new to mysql.
side note:
$c_id = $_SESSION['u_id'];
$n_id = $_GET['n_id'];
$p_id = $_GET['new_p_id'];
all of these has data, so no problem here.
Here is my query:
<?php
session_start();
include_once 'order.confirmation-header.php';
include 'includes/dbh.inc.php';
$c_id = $_SESSION['u_id'];
$n_id = $_GET['n_id'];
$p_id = $_GET['new_p_id'];
$sql = "
SELECT event_id, event_name, event_date, event_time_start,
event_time_end, cusact_id, theme, reserve_date, reserve_time
FROM event_table as e
INNER JOIN package as p
ON e.package_id = p.package_id
WHERE cusact_id = $c_id AND event_id=$n_id
";
$data = mysqli_query($conn, $sql);
if(!$data){
echo("Error description: " . mysqli_error($conn));
}
You aren't requesting any of the package columns (by merge the table I assume you mean retrieve a record set)
SELECT event_id, event_name, event_date, event_time_start,
event_time_end, cusact_id, theme, reserve_date, reserve_time, p.*
FROM event_table as e
INNER JOIN package as p
ON e.package_id = p.package_id
WHERE cusact_id = $c_id
AND event_id=$n_id
Your code is wide open to SQL injection, and I'd really consider using the PDO API with a prepared statement.

table joining to get output

I am trying to get a result by joining two tables . but i am not getting proper result . can any one tell where i am wrong ?
here is my code
$sql = "SELECT merchant.name, keyword.name
FROM keyword
INNER JOIN merchant
ON merchant.id=keyword.merchant_id";
And my table structurer is
keyword
1.name (keyword name)
2.merchant_id
merchant
1.id
2.name (merchant name)
the result sholud be like this
merchant name |||||| keyword name
and SQL fetch query is
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "<tr><td>".$row['name']."</td><td>".$row['name']."</td>";
}
But the output is
keyword name |||||| keyword name
only i am getting keyword name
can any one tell me where i am wrong . (sorry for my bad English)
Dont use mysql use Mysqli
you could try
$sql = "SELECT merchant.name as mname, keyword.name as kname FROM keyword INNER JOIN merchant ON merchant.id=keyword.merchant_id";
and
echo "<tr><td>".$row['mname']."</td><td>".$row['kname']."</td>";
Try this
$sql = "SELECT merchant.name as m_name, keyword.name as a_name
FROM keyword
INNER JOIN merchant
ON merchant.id=keyword.merchant_id";
Then
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "<tr><td>".$row['m_name']."</td><td>".$row['a_name']."</td>";
}
The issue arises because you are having two column in the query with same name and second one overrides first. Try this:
$sql = "SELECT merchant.name as mer_name, keyword.name as k_name // Aliasing for column names
FROM keyword
INNER JOIN merchant
ON merchant.id=keyword.merchant_id";
and use it like:
$row['mer_name'], $row['k_name'];

PHP get variable from on table and then use that variable to select from a second table

I'm building a followers list for a user. I have two tables the first shows the relationships between users and the second table holds every users profile info. In the following code, I first select from the user relationships table to get a variable {$userid1} which is the value of all the user ids that follow the current user. When I echo out {$userid1} I get all the ids of the users who follow the current user but it is one giant connected string. I want to take the variable {$userid1} and use it to pull every one of those follower's user data from the profile table. I want every user's data to show up from the profile table that follows the current user. The code works however only the newest follower's profile data is pulled from the profile table. I was thinking putting the variable {$userid1} into an array and using foreach, but I'm not sure how the syntax would be. Anybody know how it could work? The problem is a variable can only hold one value at a time.
Output of the first query are the iduser numbers from the users following the current user.
e.g. when echoed echo $userid1 . " "; the results are the ids look like this: 45 56 67
I added a space between numbers in the echo statement.
$sql = mysql_query("SELECT * FROM followrelations Where iduser2='$uid' "); //followers from relations table
while($row = mysql_fetch_array($sql)){
$userid1 = $row['iduser1'];
echo $userid1 . " ";
}
$sql = mysql_query("SELECT * FROM profile where iduser=$userid1 ORDER BY username ");//get followers infor from profile using variable
while($row = mysql_fetch_array($sql)){
$iduserf = $row['iduser']; //userid2 requires different var name so program does not get mixed up
$username = $row['username'];
$bio = $row['bio'];
$avatar = $row['avatar'];
echo "
<div style='width:500px;height:100px;padding:20px 20px;float:left;border: solid black 1px;'>
<a href='profile.php?uid=$iduserf'><img src=$avatar height=50px width=50px /></a></br>
<a href='profile.php?uid=$iduserf'>$username </a></br>
</div>" ;
}
You might be looking for subqueries:
SELECT username
FROM user_table
WHERE id IN( SELECT user_id WHERE linked_user_id = 123 )
This is simplefied to be a better example. This will select the username of all users from the user_table, where the ID exist in the subquery.
In turn, the subquery selects all user_id where the linked user has id=123.
The subquery is quite similar to making an array in PHP and use that info for the next query.
Small note: Be carefull with subqueries. They're perfect in my example above, but eg not all servers support a limit in the subquery. This might effect performance. The more complecated functions don't work in a subquery. Try to keep those simple.
You can use something like the following to execute this in a single query:
$id = mysql_real_escape_string($uid);
$sql = <<<SQL
SELECT
p.*
FROM profile as p
INNER JOIN followrelations as fl
ON fl.iduser1 = p.userid
WHERE fl.iduser2 = $id
ORDER BY username
SQL;
$stmt = mysql_query($sql);
while($row = mysql_fetch_array($stmt)){
// Rest of the logic here
}
This will return all the fields in your profile table. Note that the mysql_ extension is deprecated and unsafe - you should not be using it in new code. Take a look at How to replace MySQL functions with PDO? and How can I prevent SQL injection in PHP? for some good practices regarding this.
Found my mistake, the second $sql should be another name (I named it $sql1), and the second half should all be within the first while.
$sql = mysql_query("SELECT * FROM followrelations Where iduser2='$uid' "); //followers session uid
while($row = mysql_fetch_array($sql)){
$userid1 = $row['iduser1'];
$sql1 = mysql_query("SELECT * FROM profile where iduser='$userid1' ORDER BY username ");//get followers infor from profile using variable
while($row = mysql_fetch_array($sql1)){
$iduserf = $row['iduser']; //userid2 requires different var name so program does not get mixed up
$username = $row['username'];
$bio = $row['bio'];
$avatar = $row['avatar'];
echo "
<div style='width:500px;height:100px;padding:20px 20px;float:left;border: solid black 1px;'>
<a href='profile.php?uid=$iduserf'><img src=$avatar height=50px width=50px /></a></br>
<a href='profile.php?uid=$iduserf'>$username </a></br>
</div>" ;
}
}

join issue MYSQL/PHP

i have a bit of a problem, ive never used JOIN before, and this is the first time, and i got into some problems:
<?php
//$count to keep the counter go from 0 to new value
$count=0;
//I need to select the level for the users building first, meanwhile i also
//need to get the money_gain from the table buildings, which is a table that
//is common for each member, which means it doesnt have a userid as the other table!
//And then for each of the buildings there will be a $counting
$qu1 = mysql_query("SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid=$user");
while($row = mysql_fetch_assoc($qu1))
{
$count=$count+$row['level'];
echo $row['level'];
}
?>
So basically ive heard that u should tie them together with a common column but, in this case thir isnt any.. im just lost right now?
EDIT Oh right, I need the right level to be taken out with the correct money_gain too, in building_user its 'buildingid'and in buildings, its just 'id'! have no idea how to make a common statement though!
From your edit,
SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid=$user AND building_user.buildingid = building.id;
You essentially get the records for the user joining them at the building id
Performance-wise, joins are a better choice but for lightweight queries such as this, the query above should work fine.
You can also give each column a neater name
SELECT building_user.level as level,buildings.money_gain as money gain FROM building_user,buildings WHERE building_user.userid=$user AND building_user.buildingid = building.id;
and access them as
$level = $row['level'];
$gain = $row['gain'];
i think you problem is, that MySQL doesn't know how to JOIN the two Tables. Therefor you have to tell MySQL how to do that.
Example
SELECT * FROM TABLE1 INNER JOIN Table1.col1 ON TABLE2.col2;
where col1 and col2 are the columns to join (a unique identifier)
<?php
$count=0;
$qu1 = mysql_query("SELECT bu.level, bs.money_gain FROM building_user bu, buildings bs WHERE bu.userid=$user");
while($row = mysql_fetch_assoc($qu1))
{
$count=$count+$row['level'];
echo $row['level'];
}
?>
Try this
$qu1 = mysql_query("SELECT building_user.level,buildings.money_gain
FROM building_user
JOIN buildings ON building_user.building_id = buildings.id
WHERE building_user.userid=$user");
building_user.building_id is the foreght key of table building_user and
buildings.id is the primary key of table buildings

Using sql JOIN

I'm a sql noob trying to get this query to use 2 tables.
tables & columns are:
person:
department_id,
name,
etc...
department:
department_id,
dept_name,
etc...
I have a 'select' html form that the user will choose a dept_name from, and I need my php script to return every person with a matching department_id. Here is my code & query so far, I'd appeciate any help.
$search_dept = $_POST['search_dept'];
$conn = odbc_connect($odbc_name, $user_name, $pass_wd);
if ($conn) {
$query = "SELECT person.*
FROM department
JOIN person
ON department.department_id=person.department_id
WHERE department.name=$search_dept";
if($result = odbc_exec($conn, $query)) {
echo '..stuff';
while ($row = odbc_fetch_array($result)) {
...echo stuff
}
echo '...stuff';
}
else {
echo 'Query was unsuccessful';
}
}
else {
echo 'Unable to connect to database';
}
First of all, you are going about this the wrong way. You don't want to execute a WHERE clause against a text-type column if you can avoid it. Since your person table already has the department_id as a foreign key, you will want to use that value to do your selection. This means you will have to modify your select element to contain the department IDs as the options' values.
<!-- Example -->
<select name="dept_id">
<option value="1">Sales</option>
<option value="2">Support</option>
<option value="3">Fulfillment</option>
</select>
So now, not only will just the raw selection occur faster since you'll be executing against an indexed column (you did make it a proper FK so it's indexed, right?), but you will also be removing the join altogether! (which is another boost to the query's speed)
// Here is injection-safe code for the ODBC driver
$stmt = odbc_prepare( "SELECT * FROM person WHERE department_id = ?" );
$success = odbc_execute( $stmt, array( $_POST['dept_id'] ) );
// Here is the old, non-secure version, but is db-driver agnostic
$deptId = $_POST['dept_id']; // escape this please!
$query = "SELECT * FROM person WHERE department_id = $deptId";
Try this query, also make sure to escape any user input. What if the user would provide:
$_POST['search_dept']= "'; DROP TABLE person;";
Never ever ever thrust userinput!
$search_dept = mysql_escape_string($_POST['search_dept']); //make sure to escape this! you can use other functions for this as well. I'm not sure if PDO has some.
$query = "SELECT *
FROM person
JOIN department
ON department.department_id=person.department_id
WHERE department.name='$search_dept'";

Categories