Column 'name' in field list is ambiguous codigniter - mysql

this is my table structure.
tbl_user:
companyname,name,email.
tbl_userinfo:
phone,address,area,state,city,description.
tbl_category:
category_id,name.
i am joining three tables here is my model
$this->db->select(array('name', 'companyname','phone','address','email','state','city','pincode','area','description','image', 'c.name AS categoryname'));
$this->db->from('tbl_user');
$this->db->join('tbl_userinfo', 'tbl_userinfo.user_id = tbl_user.user_id');
$this->db->join ('tbl_category', 'tbl_category.category_id = tbl_userinfo.service_category');
$this->db->group_by(array('name', 'companyname', 'phone', 'address', 'email','state','city','pincode','area','description','image','categoryname'));
//$this->db->order_by('tbl_category.category_id');
$this->db->where(array('tbl_user.user_id' => 16));
i wanted third column name as well but i m getting Column 'name' in field list is ambiguous codigniter
another code that i did use but it wont show me any values for joining of two table.
$this->db->select(array('tbl_user.name', 'tbl_user.companyname','tbl_userinfo.phone','tbl_userinfo.address','tbl_user.email','tbl_userinfo.state','tbl_userinfo.city','tbl_userinfo.pincode','tbl_userinfo.area','tbl_userinfo.description','tbl_userinfo.image', 'tbl_category.name'));
$this->db->from('tbl_user');
$this->db->join('tbl_userinfo', 'tbl_userinfo.user_id = tbl_user.user_id');
$this->db->join ('tbl_category', 'tbl_userinfo.service_category = tbl_category.category_id');
$this->db->group_by(array('tbl_user.name', 'tbl_user.companyname','tbl_userinfo.phone','tbl_userinfo.address','tbl_user.email','tbl_userinfo.state','tbl_userinfo.city','tbl_userinfo.pincode','tbl_userinfo.area','tbl_userinfo.description','tbl_userinfo.image', 'tbl_category.name'));
$this->db->where(array('tbl_user.user_id' => 16));

This is most likely happening because two of your tables both have a 'name' column. I would suggest explicitly selecting the column by using [table name].[column].
$result = $this->db->query('past your query here after checking it in an sql browser');

Try this:
$user_id = '16';
$query = $this->db->select('tbl_user.companyname, tbl_user.name as UserName, tbl_user.email, tbl_userinfo.phone, tbl_userinfo.address, tbl_userinfo.area, tbl_userinfo.state, tbl_userinfo.city, tbl_userinfo.description, tbl_category.category_id, tbl_category.name as CategoryName')
->from('tbl_user')
->join('tbl_userinfo', 'tbl_userinfo.user_id = tbl_user.user_id')
->join ('tbl_category', 'tbl_category.category_id = tbl_userinfo.service_category')
->where('tbl_user.user_id', $user_id)
->group_by('tbl_user.companyname')
->get()
->result();
You can replate 'tbl_user.*' with the columns names you want to get from that table, example: 'tbl_user.user_id, tbl_user.name as UName, tbl_category.name as CName' change the name of column if you have 2 or more columns with the same name in diferent tables you are joining, it will create always an ambiguous error because there are 2 columns with the same name and codeigniter doesn't know which one you want, if you want both you need to rename the both columns.
Also add the join to left because if there is no user_id or category_id it will not display you the result.
Hope this will help you.

comes with my own code.
$this->db->select(array('u.name', 'u.companyname','i.phone','i.address','u.email','i.state','i.city','i.pincode','i.area','i.description','i.image', 'c.name AS categoryname'));
$this->db->from('tbl_user as u');
$this->db->join('tbl_userinfo as i', 'i.user_id = i.user_id');
$this->db->join ('tbl_category as c', 'c.category_id = i.service_category');
$this->db->group_by(array('u.user_id'));
$this->db->where(array('u.group_id' => 16));
$query = $this->db->get ();
return $query->result();

Related

Is there a better way to join query in laravel eloquent.?

I have two tables and both have separate models from them. first table is users and other table is users_details table I am writing an eloquent query to join the result but I am getting following error
Integrity constraint violation: 1052 Column 'gender' in where clause is ambiguous (SQL: select count(*) as aggregate from `users_details` right join `users` on `users_details`.`user_id` = `users`.`id` where `gender` LIKE female and `matrimonial` LIKE 1)
my code for the query is following.
public function bride(){
$query = app(UserDetail::class)->newQuery();
$query= $query->where('gender','LIKE','female');
$query= $query->where('matrimonial','LIKE','1');
$query = $query->rightJoin('users','users_details.user_id','=','users.id');
$request = request();
if(request()->exists('sort')){
$sorts = explode(',',request()->sort);
foreach ($sorts as $sort){
list($sortCol, $sortDir) = explode('|',$sort);
$query = $query->orderBy($sortCol,$sortDir);
}
}
else {
$query = $query->orderBy('id','asc');
}
if($request->exists('filter')) {
$query->where(function($q) use($request){
$value = "%{$request->filter}%";
$q->where('name','like',$value)
->orWhere('father_name','like',$value)
->orWhere('city','like',$value)
->orWhere('mother_name','like',$value);
});
}
$per_page = request()->has('per_page')?(int) request()->per_page : null;
$pagination = $query->paginate($per_page);
$pagination->appends([
'sort'=>request()->sort,
'filter'=>request()->filter,
'per_page'=>request()->per_page
]);
return response()->json(
$pagination
)
->header('Access-Control-Allow-Origin','*')
->header('Access-Control-Allow-Methods','GET');
}
What should I do to get the result. Thanks
Because there are same column name in your tables(gender in user_details and users), you need to specify the table name with the column, so that mysql can find the true column for you,
like this:
$query= $query->where('user_details.gender','LIKE','female');
SQL doesn't know which table you are talking about when you are using Joins - unless you specify table names for each column mentioned in your query.
Replace these lines:
$query= $query->where('gender','LIKE','female');
$query= $query->where('matrimonial','LIKE','1');
with these lines:
$query= $query->where('users_details.gender','LIKE','female');
$query= $query->where('users_details.matrimonial','LIKE','1');

DB Selecting from multiple table with join using alias in Yii2

I am trying to do a check against 3 table that I join together. I do not want to use the real table name hard coded as my project is highly under develop and table prefix may be changed. What is the best way in Yii2 to select from 3 table where I have where statement on the joined table?
I can get what I want from the code below. But as I said, I do not want to use the table alias hard coded. Any idea how to fix this or suggestion of other ideas would be very appreciated.
$userId = Yii::$app->user->id;
$result = \app\models\UserPermission::find()->joinWith([
'permission',
'permission.service'
])->where([
'prefix_user_permission.user_id' => $userId,
'prefix_permission.flag' => Permission::LOGIN,
'prefix_service.login_available' => Service::LOGIN_AVAIABLE,
])->all();
I would like to end up with this query:
SELECT *
FROM `prefix_user_permission` `up`
INNER JOIN `prefix_permission` `p` ON `up`.`permission_id` = `p`.`id`
INNER JOIN `prefix_service` `s` ON `p`.`service_id` = `s`.`id`
WHERE (`up`.`user_id`=43)
AND (`p`.`flag`='LOGIN')
AND (`s`.`login_available`=1);
The table prefix can be configured using the 'tablePrefix' param along with the main db config as follows:
'components' => [
'db' => [
//other db config params
'tablePrefix' => 'pre_'
]
This prefix can be used as follows:
There's a special variant on this syntax specific to tablenames: {{%Y}} automatically appends the application's table prefix to the provided value, if a table prefix has been set:
$sql = "SELECT COUNT([[$column]]) FROM {{%table}}";
$rowCount = $connection->createCommand($sql)->queryScalar();
Or if you are using active record for models then you can also use the tableName() function to replace the hard-coded table names.

MYSQL fetch records from table 1 that do not exist in table 2

I created a php function to fetch records from a sql table subscriptions, and I want to add a condition to mysql_query to ignore the records in table subscriptions that exists in table removed_items, here is my code;
function subscriptions_func($user_id, $limit){
$subs = array();
$sub_query = mysql_query("
SELECT `subscriptions`.`fo_id`, `subscriptions`.`for_id`, `picture`.`since`, `picture`.`user_id`, `picture`.`pic_id`
FROM `subscriptions`
LEFT JOIN `picture`
ON `subscriptions`.`fo_id` = `picture`.`user_id`
WHERE `subscriptions`.`for_id` = $user_id
AND `picture`.`since` > `subscriptions`.`timmp`
GROUP BY `subscriptions`.`fo_id`
ORDER BY MAX(`picture`.`since_id`) DESC
$limit
");
while ($sub_row = mysql_fetch_assoc($sub_query)) {
$subs [] = array(
'fo_id' => $sub_row['fo_id'],
'for_id' => $sub_row['for_id'],
'user_id' => $sub_row['user_id'],
'pic_id' => $sub_row['pic_id'],
'since' => $sub_row['since']
);
}
return $subs ;
}
My solution is to create another function to fetch the records from table removed_items and set a php condition where I call subscriptions_func() to skip/unset the records that resemble the records in subscriptions_func(), as the following
$sub = subscriptions_func($user_id);
foreach($sub as $sub){
$rmv_sub = rmv_items_func($sub[‘pic_id’]);
If($rmv_sub[‘pic_id’] != $sub[‘pic_id’]){
echo $sub[‘pic_id’];
}
}
This solution succeeded to skip the items in the table removed_items however this solution makes gaps in the array stored in the variable $sub which makes plank spots in the echoed items.
Is there a condition I can add to the function subscriptions_func() to cut all the additional conditions and checks?
Assuming id is the primary key of subscriptions and subs_id is the foreign key in removed_items, then you just have to add a condition to the WHERE clause. Something like this should work :
...
AND `subscriptions`.id NOT IN (SELECT `removed_items`.subs_id FROM `removed_items`)
...
Not related to your problem :
Your code seems vulnerable to SQL injection : use prepared statement to prevent this.
The original Mysql API is deprecated, it is highly recommended to switch to Mysqli instead.

How to retrieve every combination of numbers from 2 columns

I'm trying to find a way to retrieve every combination of values from two columns in a table, where each combination matches a value in a third column.
Say part of the table looks like this:
products_id options_id options_values_id
1487 2 1
1487 2 61
1487 3 60
1487 5 52
My desired output, when working with products_id 1487, would be the following two strings:
2-1, 3-60, 5-52
2-61, 3-60, 5-52
I've got the impression that those strings would need to be assembled recursively, but I ran into trouble trying it that way because not every products_id has the same options_ids, or the same number of them.
Edited to add: I've tried variations of a couple of the solutions below, but to no avail. I think I should have been more descriptive.
I'm trying to have it retrieve every combination of unique options_id and its corresponding options_values_id. (In other words, not every single possible combination of numbers from those two columns.) Options_id represents product options like "color" and "size," and options_values_id represents choices of those options, like "red" or "small." So I'm trying to come up with every possible combination of options for a given products_id. In the example above, there are two possible option combinations for that item-- "2-1, 3-60, 5-52" and "2-61, 3-60, 5-52".
Join the table against itself for each distinct option.
Do a select first to retrieve the number of options.
$tables = array();
$rs = mysql_query(
'SELECT DISTINCT options_id FROM table WHERE products_id = '.$id);
while ($row = mysql_fetch_row($rs)) {
$tables[$row['options_id']] =
'SELECT options_values_id FROM table WHERE products_id = '.$id.
' AND options_id = '.$row['options_id'];
}
mysql_free_result($rs);
Then, for each option, join it in as a separate table in your query. Do not include any joining clauses comparing values, just join every record against every other record.
$sql = 'SELECT ';
$count = 0;
foreach ($tables AS $id => $query) {
if ($count++) $sql .= ', ;
$sql .= 'table_'.$id.'.options_values_id AS value_'.$id;
}
$sql .= ' FROM ';
$count = 0;
foreach ($tables AS $id => $query) {
if ($count++) $sql .= ', ';
$sql .= '('.$query.') AS table_'.$id;
}
Finally, execute that query. Each row will contain one column per options_id. There will be one row per unique combination of values.
or for a mixed, php/sql approach, try using that SQL query:
SELECT products_id, options_id, options_values_id WHERE products_id = '$var_with_product_id';
fetch the results into an array, say $results:
$pairs = array();
foreach($results as $result) {
// build array with pairs (array_push to avoid overwriting)
array_push($pairs, array( $result['options_id'] => $result['options_values_id'];
}
// a bit extra complication, as array_push adds e.g. [0] => array( options_id => options_values_id ) :)
$pairs = array_values($pairs);
// check for double options_id
$found_double_options_id = false;
do {
// check for duplicates... use a lot of array functions
} while (count($pairs) && $found_double_options_id);
"Every combination" is the Cartesian product:
SELECT DISTINCT e1.options_id, e2.options_values_id
FROM Entity e1, Entity e2
WHERE e1.products_id = 1487 AND e2.products_id=1487

What is the correct syntax for a select query in drupal

If I have a table named book
Column 1 = current_user
, Column 2 = page_length
, Column 3 = author
, Column 4 = title
I'd like to select the data from columns 2, 3 and 4 that correspond to the currently logged in user. Is the following correct syntax?
<?
global $user;
$user_id=$user->name;
db_query('SELECT * FROM {book} WHERE current_user=$user_id', $page_length, $author, $title); ?>
Some tips:
You need to make sure to use quotation marks around the string that is the SQL statement.
Since the username is a user-supplied string, you should use parameter escaping to prevent SQL injections.
You don't really need to assign the user name to a separate variable ($user_id) to use it.
You need to retrieve your result from the return value of db_query.
Fixed code:
<?php
global $user;
$res = db_query("SELECT page_length, author, title FROM {book} WHERE current_user = '%s'", $user->name);
$row = db_fetch_array($res);
// now $row['page_length'], $row['author'] and $row['title'] are filled in with values if the query was successful
?>