PHP left join not displaying results - php

I am trying to left join to tables in PHP. I am a total noob to left join and I can't figure out what I'm doing wrong!
$value=$_GET['value'];
$storeid=$_GET['store'];
$id=$_GET['id'];
$latitude=$_GET['lat'];
$longitude=$_GET['long'];
$result = mysqli_query($con,"SELECT carlist.id, carlist.vin, link_qr.qr, link_qr.vin
FROM link_qr, carlist LEFT JOIN link_qr.vin ON carlist.vin
WHERE qr="$value";");
while($row = mysqli_fetch_array($result)) {
echo $row['id'];
echo $row['vin'];
echo $row['qr'];
}
Here is the table structure
Table: link_qr
id------vin---------qr------webid---------other
Table: carlist
id---stknum---vin----vt----stat---other---store_id---web_code---qrcode
When all done I would like to have the following.
I would like to join the carlist and the link_qr where the vins are equal to each other and then I need it to return the carlist id where that vin is equal to qr.
Here are the errors I'm getting:
**Notice: Undefined index: store in /api/app_request/left_join.php on line 13
Notice: Undefined index: id in /api/app_request/left_join.php on line 14
Notice: Undefined index: lat in /api/app_request/left_join.php on line 15
Notice: Undefined index: long in /api/app_request/left_join.php on line 16
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in api/app_request/left_join.php on line 22**

There are a couple things to note:
First, your SQL query is incorrect:
SELECT carlist.id, carlist.vin, link_qr.qr, link_qr.vin
FROM carlist
LEFT JOIN linkqr ON linkqr.vin=carlist.vin
WHERE qr="$value";
Should be the correct format so long as those tables and columns exist. Secondly, however, you should not be querying a database with an unescaped value. This leads to SQL Injection. More appropriately you could write your query like:
$query = <<<SQL
SELECT carlist.id, carlist.vin, link_qr.qr, link_qr.vin
FROM carlist
LEFT JOIN linkqr ON linkqr.vin=carlist.vin
WHERE qr=?
SQL;
$stmt = mysqli_prepare($query);
mysqli_bind_param($stmt, "s", $value); // this sets the ? in the sql query to $value
mysqli_execute($stmt);
$result = mysqli_get_result($stmt);
while($row = mysqli_fetch_array($result)) {
echo $row['id'];
echo $row['vin'];
echo $row['qr'];
}

Why not do:
"SELECT C.PrimaryId, Field, AnotherField
FROM tablename AS C
LEFT JOIN tablename AS L ON C.matching_id = T.matching_id
WHERE tablename.fieldname = :fieldname
?

Related

Join columns from two mysql tables

I'm trying to figure out the following. In the beginning I want to check if a member is in groups 11, 43 or 1.
I have the following tables with columns:
table members (member_id, name, group)
334 Ronald 43
table content (member_id, value)
334 Gold
I'm looking for a query which displays the name FROM members and value FROM content, joined with member_id and end result something like
Ronald Gold
If the user is not in the groups I have set, he/she will not be displayed.
The following is what i have managed to do
$sql = 'SELECT * FROM members m INNER JOIN content p ON m.member_id = p.member_id ';
$retval = mysql_query( $sql, $conn );
and
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo $row['member_id']. " " .$row['value'];
echo "<br>";
}
will output 334 Gold.
I just need to check the group in the beginning and replace member_id with name in the final output. Any help?
Just adjust your mysql query:
$sql = 'SELECT m.name, p.value FROM members m JOIN content p ON m.member_id = p.member_id WHERE m.group = 1 OR m.group = 11 OR m.group = 43;
then
echo $row['name']. " " .$row['value'];
Also you should be using mysqli_query() or PDO::query() since mysql_query() is deprecated. Reference
When you're echoing the results if you change echo $row['member_id'] to echo $row['name'] you will get the member's name.
Returning $row['group'] will tell you which group the member is in.
Your SQL should return following construct for each row
(member_id, name, group, value)
to filter out members not in desired groups modify your query
$sql = 'SELECT * FROM members m INNER JOIN content p ON m.member_id = p.member_id WHERE m.group IN (11,43,1) ';
Side note:
Consider using PDO or mysqli_* instead of mysql_* as mysql_* is deprecated and gone in PHP7

Multiple mysql table joins with php?

Honestly I have no idea how to do what I am trying to do. I am not overly experienced in php nor in Mysql but I am trying and could use some help, preferably with working example code.
Problem: I have 3 tables
members
customfields
customvals
members contains:
membername | Id
customfields contains:
rank | name
customvals contains
fieldid | userid | fieldvalue
Table columns match at
customvals.userid=members.id
customvals.fieldid=members.rank
What I need to do is match the data so that when page.php?user=membername is called it displays on the page
Table1.membername:<br>
Table2.name[0] - Table3.fieldvalue[0]<br>
Table2.name[1] - Table3.fieldvalue[1]<br>
etc...
(obviously displaying only the information for the said membername)
The more working the code, the more helpful it is for me. Please don't just post the inner join statements. Also it is most helpful to me if you could explain how and why your solution works
So far here is what I have for code:
$profileinfocall = "SELECT Table1.`membername`, Table2.`name`, Table3.`fieldvalue`
FROM members AS Table1
LEFT JOIN customvals AS Table3 ON Table1.`id` = Table3.`userid`
LEFT JOIN customfields AS Table2 ON Table3.`fieldid` = Table2.`rank`
WHERE Table1.`membername` = $username;";
$membercall = "SELECT * FROM members WHERE membername=$username";
$profileinfo = mysql_query($profileinfocall, $membercall);
while($row = mysql_fetch_array($profileinfo)) {
echo $row['membername'];
}
Obviously this doesn't work as I get the following errors:
Warning: mysql_query() expects parameter 2 to be resource, string given on line 534.
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in on line 535
While this is a very broad question and you have not provided any PHP code, you might want to break it down into various sections:
Establishing a connection to the database (with mysqli) and sending a query:
$c = mysqli_connect("localhost","user","password","db");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
else {
$result = mysqli_query($c,"SELECT * FROM members");
while($row = mysqli_fetch_assoc($result)) {
echo "{$row['membername']}";
}
}
mysqli_close($c);
Tieing your tables together:
It is better to start off with a clear structure (including line breaks) when getting into the MySQL syntax. One way would be to have some sort of query skeleton:
SELECT tablealias.column, table2alias.field3
FROM table AS tablealias
LEFT|RIGHT|INNER JOIN table2 AS table2alias ON table.id=table2.id
WHERE (this and that = true or false, LIKE and so on...)
Breaking it down to your specific problem this would be:
SELECT Table1.`membername`, Table2.`name`, Table3.`fieldvalue`
FROM members AS Table1
LEFT JOIN customvals AS Table3 ON Table1.`id` = Table3.`userid`
LEFT JOIN customfields AS Table2 ON Table3.`fieldid` = Table2.`rank`
WHERE Table1.`Id` = 'UserID to be searched for'
Improvements & Security measures:
But there is even more to it than meets the eye. If you have just begun, you might as well dive directly into prepared mysqli- statements. Given the query to get your members, the only changing part is the ID. This can be used for a prepared statement which is much more secure than our first query (though not as fast). Consider the following code:
$sql = "SELECT Table1.`membername`, Table2.`name`, Table3.`fieldvalue`
FROM members AS Table1
LEFT JOIN customvals AS Table3 ON Table1.`id` = Table3.`userid`
LEFT JOIN customfields AS Table2 ON Table3.`fieldid` = Table2.`rank`
WHERE (Table1.`Id` = ?)";
$c = mysqli_connect("localhost","user","password","db");
$stmt = $c->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_params("i", $userid);
$stmt->execute();
while ($stmt->fetch()) {
//do stuff with the data
}
$stmt->close();
}
$mysqli->close();
This SQL query should do it:
SELECT a.membername, a.Id, b.fieldid, b.userid, b.fieldvalue, c.rank, c.name
FROM members AS a
LEFT JOIN customvals AS b ON a.id = b.userid
LEFT JOIN customfields AS c ON b.rank = c.fieldid
WHERE a.Id = #MEMBERIDHERE#;

Undefined index PHP/MySQL when trying to query database

This one is working fine #1 but when I try to relate other tables on the second one, it gives an error
Notice: Undefined index: recipe.id in C:\xampp\htdocs\hyukies\public\samples.php on line 30
Notice: Undefined index: recipe.ingredientid in C:\xampp\htdocs\hyukies\public\samples.php on line 31
RecipeID:
IngredientID:
Notice: Undefined index: recipe.id in C:\xampp\htdocs\hyukies\public\samples.php on line 30
Notice: Undefined index: recipe.ingredientid in C:\xampp\htdocs\hyukies\public\samples.php on line 31
RecipeID:
IngredientID:
Notice: Undefined index: recipe.id in C:\xampp\htdocs\hyukies\public\samples.php on line 30
Notice: Undefined index: recipe.ingredientid in C:\xampp\htdocs\hyukies\public\samples.php on line 31
RecipeID:
IngredientID:
<?php
$sql = mysqli_query($connection, "SELECT id, location FROM location");
$userinfo = array();
while ($row_user = mysqli_fetch_assoc($sql))
$userinfo[] = $row_user;
foreach ($userinfo as $user) {
echo "ID: {$user['id']}<br />"
. "Location: {$user['location']}<br /><br />";
}
?>
This one is not working error problem please help......
<?php
$sql_2 = mysqli_query($connection, "SELECT recipe.id, recipe.ingredientid, ingredients.id, ingredients.quantity, ingredients.`name` FROM recipe INNER JOIN ingredients ON ingredients.id = recipe.ingredientid");
$userinfo_2 = array();
while ($row_user_2 = mysqli_fetch_assoc($sql_2))
$userinfo_2[] = $row_user_2;
foreach ($userinfo_2 as $user_2) {
echo "RecipeID: {$user_2['recipe.id']}<br />"
. "IngredientID: {$user_2['recipe.ingredientid']}<br /><br />";
}
?>
Remove the back ticks from 'name' in your query
$sql_2 = mysqli_query($connection, "SELECT recipe.id, recipe.ingredientid, ingredients.id, ingredients.quantity, ingredients.`name` FROM recipe INNER JOIN ingredients ON ingredients.id = recipe.ingredientid");
Should be
$sql_2 = mysqli_query($connection, "SELECT recipe.id, recipe.ingredientid, ingredients.id, ingredients.quantity, ingredients.name FROM recipe INNER JOIN ingredients ON ingredients.id = recipe.ingredientid");
Also, remove 'recipe' from $user_2['recipe.id']. It should be $user2['id'], but it won't be clear which id you are getting. To selected them independently you can use 'AS' in your query to give them a unique identifier.
SELECT recipe.id AS id1, ingedients.id AS id2
The keys in the associative array just contain the column names, not the table names. So it should be:
echo "RecipeID: {$user_2['id']}<br />"
. "IngredientID: {$user_2['ingredientid']}<br /><br />";
The table names are not included in the result set, so the columns are only named id, ingredientid etc. You really should use as for naming them, like recipe.id as recipeid. There is no warning about there being to id fields and PHP will map them together.
You don't really need both id fields anyway, since you also have the ingredientid, but most probably you will get ingredients.id in the id field also since it's latter.
So update your query to something like
SELECT recipe.id AS recipeid,
recipe.ingredientid,
ingredients.quantity,
ingredients.name
FROM recipe
INNER JOIN ingredients ON ingredients.id = recipe.ingredientid
and then use recipeid to get the recipe.id. This will always be better, since it's clear what id you are getting.

codeigniter calendar class error message

I use codeigniter calendar class and i am trying to display all reservations for the current month. In the field where the day is, I may have more than one result,and I would like to display them coma separated.
However, I get the following error message:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$reservationID
Filename: models/reservationcalendarmodel.php
Line Number: 81
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$reservationArrivalDate
Filename: models/reservationcalendarmodel.php
Line Number: 81
Error is displayed 10 times ( i expect 9 records from the database)
Here is the (relevant) code from the model:
function getReservations($year,$month) {
$currentHotelUser = $this->session->userdata('currentHotelUser');
$query = $this->db->query(
"SELECT r.*
FROM room r
LEFT JOIN (SELECT rr.roomID, re.reservationID,re.reservationArrivalDate
FROM reservationroom rr
LEFT JOIN reservation re ON re.reservationID = rr.reservationID
WHERE re.reservationArrivalDate LIKE('".$year."-".$month."-%'))
sq ON sq.roomID = r.roomID
WHERE r.hotelID = ".$currentHotelUser['hotelID']."
AND sq.reservationID IS NOT NULL
");
$cal_data = array();
foreach($query->result() as $row) {
// BELLOW IS THE LINE 81 WHERE THE ERROR IS
$cal_data[substr($row->reservationArrivalDate,8,2)]= $row->reservationID;
}
return $cal_data;
}
function generate($year,$month) {
$cal_data = $this->getReservations($year, $month);
$this->load->library('calendar', $this->conf);
return $this->calendar->generate($year,$month,$cal_data);
}
Here is the (relevant) code from the controller:
$this->load->model('ReservationCalendarModel');
$data['calendar'] = $this->ReservationCalendarModel->generate($year,$month);
Here is the (relevant) code from the view:
echo $calendar;
Did anyone know why do I get the above error?
The problem is you query results not having reservationID and reservationArrivalDate. That is the reason, while looping through you are getting this error. Add these two columns in your main select query
"SELECT r.*, sq.roomID, sq.reservationId
FROM room r
LEFT JOIN (SELECT rr.roomID, re.reservationID,re.reservationArrivalDate
FROM reservationroom rr
LEFT JOIN reservation re ON re.reservationID = rr.reservationID
WHERE re.reservationArrivalDate LIKE('".$year."-".$month."-%'))
sq ON sq.roomID = r.roomID
WHERE r.hotelID = ".$currentHotelUser['hotelID']."
AND sq.reservationID IS NOT NULL
"

Get earliest year from multiple tables

I have a couple tables where there is a same field added. What I want to do is get the earliest year from all these records.
Tables:
comics | movies | tv | tv_episodes
Code So Far (Doesn't Work):
function getStartYear() {
include("config.php");
$query = "SELECT DATE_FORMAT(added, '%Y') as `added` FROM (comics,movies,tv,tv_episodes) ORDER BY `added` DESC LIMIT 1";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
return $row['added'];
}
}
Error Returned:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in E:\xampp\htdocs\mydb\functions\common.php on line 94
What would be the most efficient way to do this?
UPDATE
So going by Andrew's answer the new query looks like:
function getStartYear() {
include("config.php");
$query = "SELECT MIN(y) FROM (
SELECT MIN(YEAR(added)) AS y FROM comics
UNION SELECT MIN(YEAR(added)) AS y FROM movies
UNION SELECT MIN(YEAR(added)) AS y FROM tv
UNION SELECT MIN(YEAR(added)) AS y FROM tv_episodes
) AS t1";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$finalanswer = mysql_fetch_array($result);
return $finalanswer['t1']; // <-- Line 96
}else{
echo mysql_error();
}
}
New Message:
Notice: Undefined index: t1 in E:\xampp\htdocs\mydb\functions\common.php on line 96
Could retrieve it through SQL using a UNION sub-query:
SELECT MIN(y) FROM (
SELECT MIN(YEAR(added)) AS y FROM table1
UNION SELECT MIN(YEAR(added)) AS y FROM table2
...
) AS t1;
First you should be checking to make sure your SQL statement actually returns the desired data. Run the script itself in some sort of SQL viewer (or phpMySQL), or
echo mysql_error();
just to be sure you don't have an invalid SQL statement.
The invalid resource error you're getting indicates to me that the "$result" of your mysql_query function is not a valid resource.
So:
if (!$result = mysql_query($query))
echo mysql_error();
if you do have an error in your query, diagnose and fix and go from there...
As it stands right now, you're doing a "return" from the middle of a loop, which means you're returning the first object found in the result set.
I would consider instead of "looping", do this:
if (mysql_num_rows($result) > 0)
{
$finalanswer = mysql_fetch_array($result);
return $finalanswer['added'];
}
else
echo mysql_error();
error trapping is kind of a nice thing to get in the habit of. :)

Categories