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'];
Related
I have two tables, one is a user log which stores the user by number
timestamp / user_id / transaction_id / amount
the other is a user table which has the users number and their full name
user_id / fullname
I want to select the entire user log and display it, but instead of displaying their number, display their full name from the other table, but I can't get it working. I keep modifying the sql and breaking it. Is there a way to accomplish this with php postgresql or should I use a function?
I keep getting an error that user_id is integer and the fullname is not
Please assist.
$query = "SELECT * FROM user_log
INNER JOIN user_staff
ON user_log.user_id=user_staff.user_name
ORDER BY user_log_id DESC LIMIT 200;";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['timestamp'], htmlspecialchars($myrow['user_id']), htmlspecialchars($myrow['transaction_id']), htmlspecialchars($myrow['amount']));
}
?>
Use this query:
SELECT "timestamp", fullname, transaction_id, amount
FROM user_log
JOIN users USING (user_id)
Note that "timestamp" is a SQL reserved word and you should not use it for a column name. If you must use it, put it in double quotes.
Perhaps something like:
SELECT user_log.timestamp, users.fullname, user_log.transaction_id, user_log.amount
FROM user_log
INNER JOIN users
ON users.user_id=user_log.user_id
ORDER BY user_log_id
DESC LIMIT 200;
You can read up on SQL Joins here: http://www.w3schools.com/sql/sql_join.asp
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;
?>
Scenario:
I am working on a PHP/MySQLi aplplication where I have got 2 tables attendance and students .
students has fields: student_id, fullname, phone,email,gender, department and level.
attendance table has fields: attendance_id, student_id, department_id, level_id.
I was able to fetch all students whose records are in the attendance table according to their department and level.
Question:
Let's assume that I was able to fetch all students whose records are in the attendance table and are in 200L (with level_id, 2) computer science (with department_id, 4) department, if the list of the students present are much and it was paginated and I want to search for a particular student's fullname that's in attendance table in reference to student's table.
How will the SQL query be like? I tried the following query which didn't work.
$search_query = mysqli_query($db_connect, "SELECT *FROM attendance WHERE student_id=\"SELECT student_id FROM students WHERE fullname LIKE '%$student_fullname%'\";
Please help.
Try this query:
SELECT attendance.*
FROM `students`
INNER JOIN `attendance`
ON `attendance`.`student_id` = `students`.`student_id`
WHERE `students`.`fullname` LIKE `%$student_fullname%`
I know that may look back-to-front at first, but I prefer to structure the SQL to show the strong selector (the LIKE filter) in the WHERE clause. If you do not like that, you can get the same result like this:
SELECT attendance.*
FROM `attendance`
INNER JOIN `students`
ON `students`.`student_id` = `attendance`.`student_id`
AND `students`.`fullname` LIKE `%$student_fullname%`
Note that this second version does NOT have a WHERE clause - always put filters on the RHS of a join in the join's ON clause, because otherwise outer joins will not behave correctly.
The SQL query you are looking for is:
select * from attendance join students on attendance.student_id = students.student_id where students.fullname like '%NAME%'
so in PHP you would need something like:
$query_string = "select * from attendance join students on attendance.student_id = students.student_id where students.fullname like '%$student_fullname%'";
$search_query = mysqli_query($db_connect, $query_string);
I would recommend you to have a look at prepared statements though, to prevent SQL injection: http://php.net/manual/en/mysqli.prepare.php
/* create a prepared statement */
$query_string = "select * from attendance join students on attendance.student_id = students.student_id where students.fullname like ?";
if ($stmt = $mysqli->prepare($query_string)) {
$stmt->bind_param("s", $student_fullname);
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc()) {
// use your $myrow array as you would with any other fetch
printf("%s found in attendance record ID: %s\n", $student_fullname, $myrow['attendance_id']);
}
$stmt->close();
}
I am trying to select everything from two different mysql tables. I imploded an array called friends so that I can select everything about the user's friends from both tables. Originally I wanted to perform one query on one table and then in a while loop a query on the other. But that didn't work. If you know I way I can nest while loops then please be sure to comment/answer this question.
Here's my code:
$friends = implode("','", $friends);
//implode the friends array for sql query
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
echo '<br><br>';
}
Note: $row['last_name'] is from the users table and $row['body'] is from the text_post table. I am receiving this error whenever I run my code Column 'username' in where clause is ambiguous
Please help me.
UPDATE:
I changed my query to: $sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends')") or die(mysqli_error($con)); but now it echo's every match twice:
parker hello
parker hello
simms what is up
simms what is up
simms it's raining
simms it's raining
jorge potato
jorge potato
Why is it doing that?
The only thing that is the same in both tables is the username.
Thanks for your question. The issue here is the error that you are receiving of:
Column 'username' in where clause is ambiguous.
What this means is that the statement that you are running is too obscure.
What you need to do to avoid this is to explicitly define the tables and columns that you are attempting to access and thus be implicit in your statements.
As a rule of thumb try and always define your columns in the following format:
{table_name}.{column_name}
With that being said the following should work:
$friends = implode("','", $friends);
/* implode the friends array for sql query. */
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends') AND text_post.username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
}
Also I would also recommend that you use PHP's PDO Object as appose to the mysqli_query method.
I trust this helps.
both tables have a username. specify it using table.username
apparently both tables have the same column, and you are not prefixing the username column with either table name.
Maybe what you want is a union?
Use table prefix users in where block i.e. users.username
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends')") or die(mysqli_error($con));
Try this:
$friends = implode("','", $friends);
//implode the friends array for sql query
$sql = mysqli_query($con, "SELECT users.last_name,text_post.body FROM users, text_post WHERE username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
}
Your logic would work were it not for username being present in both tables. Because it is, you need to alias your table names so that you can uniquely identify which column you're trying to use in the where clause:
SELECT * from users AS u, text_post as tp
WHERE u.username IN(....)
or shorter:
SELECT * from users u, text_post tp
WHERE u.username IN(....)
As a side note, it's bad practice to SELECT *, you should always explicitly select the columns you want, otherwise your code may crash if you add a column to a table later and forget to update your for loop to include/ignore any changed columns.
my problem is i want to JSON_ENCODE the result of inner join query and the two columns i want to select have the same name so, the JSON object override one of them and carry only data for one column cause they have the same name,,this is my code till now.
$query = "select faculty.NAME,sector.NAME from faculty inner join sector
on faculty.SECTOR_ID=sector.ID";
$result = mysql_query($query);
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
how to do this without change the column name in the DataBase...
Try changing the output of your query:
select faculty.NAME AS facultyName,sector.NAME AS sectorName from faculty inner join sector
on faculty.SECTOR_ID=sector.ID
Using as:
select faculty.NAME as faculty_name, sector.NAME as sector_name from faculty inner join sector
on faculty.SECTOR_ID=sector.ID
This will change your json values to something like:
{"faculty_name": "first", "sector_name": "second"}
so you will need to update your javascript.
You can use ALIAS In your query so you will have different names for your columns
select faculty.NAME as faculty_name ,sector.NAME as sector_name