MySql select from 3 tables Undefined index error - php

I have 3 tables tbl_user,tbl_supplier,tbl_subcontractor
I want to select this rows from
tbl_user (db_fname,db_lname),
tbl_supplier(db_CompanyName),
tbl_subcontractor(db_CompanyName)
I'm using this query
SELECT concat(db_fname,' ',db_lname) as fname from tbl_user)
UNION
(SELECT db_CompanyName as scn from tbl_supplier)
UNION
(SELECT db_CompanyName as sucn from tbl_subcontractor)
It give me the correct result but also give me this error
( ! ) Notice: Undefined index: scn in
C:\wamp\www\order\projectmanagment\transferred.php on line 48 Call
Stack #TimeMemoryFunctionLocation 10.0021260912{main}(
)..\transferred.php:0 ( ! ) Notice: Undefined index: sucm in
C:\wamp\www\order\projectmanagment\transferred.php on line 49 Call
Stack #TimeMemoryFunctionLocation 10.0021260912{main}(
)..\transferred.php:0
the result of this query will be display on a select menu like this:
echo'<select name="txt_transferredto" class="states">';
while($row=mysqli_fetch_array($q)){
$fname=$row['fname'];
$companyname=$row['scn'];
$subcompanyname=$row['sucm'];
if($fname!=""){
echo"<option value='$fname'>";echo $fname;echo"</option>";}
else if($subcompanyname!=""){
echo"<option value='$subcompanyname'>";echo $subcompanyname;echo"</option>";}
else if($companyname!=""){
echo"<option value='$companyname'>";echo $companyname;echo"</option>";}
}
echo'</select>';
in this menu appear the result but also the error
i can select from this menu the data take it from tbl_user and do what ever i want but also if i select data take it from tbl_supplier or tbl_subcontractor i can't do anything(update or select or ...)
i test on sql and give me result but i don't know what is this problem
How to solve this Problem
$q=mysqli_query($conn,"SELECT concat(db_fname,' ' , db_lname) as fname from tbl_user ") or die(mysqli_error($conn));
$qq= mysqli_query($conn,"SELECT db_CompanyName as scn from tbl_supplier") or die(mysqli_error($conn));
$qqq= mysqli_query($conn,"SELECT db_CompanyNamee as sucn from tbl_subcontractor") or die(mysqli_error($conn));
echo'<select name="txt_transferred" class="form-control inpu-md">';
echo'<option value="">--SELECT--</option>';
while($row=mysqli_fetch_array($q) and $roww=mysqli_fetch_array($qq) and $rowww=mysqli_fetch_array($qqq)){
$fname=$row['fname'];
$companyname=$roww['scn'];
$subcompanyname=$rowww['sucn'];
if($fname!=""){
echo"<option value='$fname'>";echo $fname;echo"</option>";}
else if($subcompanyname!=""){
echo"<option value='$subcompanyname'>";echo $subcompanyname;echo"</option>";}
else if($companyname!=""){
echo"<option value='$companyname'>";echo $companyname;echo"</option>";}
}
echo'</select>';

I think your query should be:
SELECT concat(db_fname,' ',db_lname) as fname ,
S.db_CompanyName as scn, SC.db_CompanyNam as sucn
FROM tbl_user U, tbl_supplier S, tbl_subcontractor SC

Related

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.

Display two tables select values in select option

I have two tables (client_login,co_passenger).i want to display fname from both tables in select box.i have tryed this.but it display fname from only one table.
<select name="client" class="category_list" id="dynamic_select" >
<?php
$query= "SELECT c.fname,p.fname FROM client_login c,co_passenger p" ;
$result= mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
echo '<option value="directory.php?cat_id='.$row['fname'].'">'.$row['fname'].'</option>';
}
?>
</select>
i want to display aa,bb,cc,dd in select box
client_login
co_passenger
You have to use two queries merged together using union
$query= "SELECT fname FROM client_login
union
select fname from co_passenger "
This will return combined results.

PHP left join not displaying results

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
?

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. :)

Pick rows from one table but where statement condition is in another table

I have 2 tables, I have to get the data of one table using where = "this value in some other table"
users_info and users_frnds
users_info look like this
name image presently id
somename somimage studying 2
somename somimage studying 3
users_frnds table looks like this
userid friendid
1 2
1 3
$query = "SELECT * FROM users_info WHERE users_info.id =
users_frnds.friendid";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['image'];
echo "<br />";
but it does not seem to work here. I wanted to get all the data at once into my array.
It throws me this error:
Unknown column 'users_frnds.friendid' in 'where clause'
You will need to join, like:
SELECT specifyfields
FROM users_friends
INNER JOIN users_info ON users_info.id=users_friends.friendid
Then you will get access, try never to join tables in the WHERE clause because that can create quite unreadable queries.

Categories