Column 'id' in field list is ambiguous - mysql

I am getting the follwing error, Column 'id' in field list is ambiguous. how can i uniquely grab the correct ID from this statment
function data () {
if($at = mysql_real_escape_string(#$_GET['id'])){$at = mysql_real_escape_string(#$_GET['id']);
$arg = func_get_args();
unset($arg[0]);
$fields = '`'.implode('`,`', $arg).'`';
$query = mysql_query("SELECT $fields FROM `list` LEFT JOIN fruits ON location.id =
fruits.fid
LEFT JOIN store ON store.id = location.catid WHERE location.link = '$at'")or die(mysql_error());
$query_result = mysql_fetch_assoc($query);
$query_row = mysql_num_rows($query);
if($query_row==0){
return false;
}else{
foreach ($arg as $field){
$arg[$field] = $query_result[$field];
}return $arg;
}
}
}

$fields = '`list`.'.implode('`, `list`.`', $arg).'`';
But I strongly recommend Doctrine!

Seems to be a problem in your mysql query. Specifying the name of the table along with the name of your field would be the easiest solution I guess:
$fields = 'tablename'.$fields;

Turns that it is easier to just change the name of one the id in the table.

Related

How to convert sql query to codeigniter query

Can somebody help me convert this Sql Query
SELECT *
FROM customer c
LEFT JOIN customer_order co
ON c.customer_number = co.customer_number
AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid'
AND c.order_status = 'unserve'
AND co.cus_ord_no IS null
into Codeigniter query just like the image below for example
When query statements do not have clauses that need to change conditionally then using $this->db-query() is the way to go.
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co
ON c.customer_number=co.customer_number AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid' AND c.order_status='unserve' AND co.cus_ord_no IS null";
$query = $this->db->query($sql)->result();
echo json_encode($query);
It might be wise to include a check on the return from query() though because if it fails (returns false) then the call to result() will throw an exception. One way that can be handled is like this.
$query = $this->db->query($sql);
if($query !== FALSE)
{
echo json_encode($query->result());
return;
}
echo json_encode([]); // respond with an empty array
Query Builder (QB) is a nice tool, but it is often overkill. It adds a lot of overhead to create a string that literally is passed to $db->query(). If you know the string and it doesn't need to be restructured for some reason you don't need QB.
QB is most useful when you want to make changes to your query statement conditionally. Sorting might be one possible case.
if($order === 'desc'){
$this->db->order_by('somefield','DESC');
} else {
$this->db->order_by('somefield','ASC');
}
$results = $this->db
->where('other_field', "Foo")
->get('some_table')
->result();
So if the value of $order is 'desc' the query statement would be
SELECT * FROM some_table WHERE other_field = 'Foo' ORDER BY somefield 'DESC'
But if you insist on using Query Builder I believe this your answer
$query = $this->db
->join('customer_order co', "c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared')", 'left')
->where('c.customer_status','unpaid')
->where('c.order_status','unserve')
->where('co.cus_ord_no IS NULL')
->get('customer c');
//another variation on how to check that the query worked
$result = $query ? $query->result() : [];
echo json_encode($result);
You can do
public function view_customers()
{
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co ON c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared') WHERE c.customer_status='unpaid' AND c.order_status = 'unserve' AND co.cus_ord_no IS null";
return $this->db->query($sql)->result();
}
You can use row() for one output to object, or row_array() if one output but array. result() is multiple objects and result_array() is multiple arrays.
My way do usually is like this:
Controller:
public function view()
{
$this->load->model('My_Model');
$data = new stdclass;
$data->user_lists = $this->my_model->view_users(array('nationality'=>'AMERICAN'));
}
Model:
public function view_users($param = null) //no value passed
{
$condition = '1';
if (!empty($param)) { //Having this will trap if you input an array or not
foreach ($param as $key=>$val) {
$condition .= " AND {$key}='{$val}'"; //Use double quote so the data $key and $val will be read.
}
}
$sql = "SELECT * FROM users WHERE {$condition}"; //Use double quote so the data $condition will be read.
// Final out is this "SELECT * FROM users WHERE 1 AND nationality='AMERICAN'";
return $this->db->query($sql)->result();
}

SQL in Drupal. WHERE AND

The following works...
global $user;
$items = array();
$sql = 'SELECT nid FROM {node} WHERE uid = :uid';
$result = db_query($sql, array(':uid' => $user->uid));
foreach ($result as $row) {
$items[] = $row->nid;
}
dsm($items);
However, when I want to select the content type "venue" from the "type" column in the same database tables, I get errors using the following...
global $user;
$items = array();
$sql = 'SELECT nid FROM {node} WHERE uid = :uid AND type = venue';
$result = db_query($sql, array(':uid' => $user->uid));
foreach ($result as $row) {
$items[] = $row->nid;
}
dsm($items);
DOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'venue' in 'where clause': SELECT nid FROM {node} WHERE uid = :uid AND
type = venue; Array ( [:uid] => 1 )
Im ovbiously not understanding something here. The column is called "type", im not asking it to look for a column called "venue" am i?
When comparing a column to a string you need to wrap the string with quotes, if you dont, the optimizer will see this as a column(unless its a number) . Try this:
$sql = "SELECT nid FROM {node} WHERE uid = :uid AND type = 'venue'"

default image if file not exist mysql pdo

I'm trying to add a default image in a query, if the file does not exist.
I succeeded when the query doesn't have a while loop. But since i need to loop this values. i would like to add the default image to the query.
I wont get any errors, its just printing out some random info from my DB.
function fetch_tweets($uid){
$uid = (int)$uid;
$query = $this->link->query
("SELECT user.id, user.email, user.username, tweets.message, tweets.date,
userdetails.profile_img, userdetails.firstname, userdetails.lastname,
following.id, following.user_id, following.follow_id
FROM user
LEFT JOIN
following ON user.id = following.user_id
JOIN userdetails ON user.id = userdetails.user_id
JOIN tweets ON userdetails.user_id = tweets.user_id
WHERE user.id='{$uid}'
OR
user.id IN (SELECT follow_id
FROM following
WHERE
following.user_id = '{$uid}' )
GROUP BY tweets.date ORDER BY tweets.date DESC "
);
$tweet = array();
while(($row = $query->fetch(PDO::FETCH_ASSOC)) !==FALSE) {
$tweet[] = $row;
$tweet['profile_img'] = (file_exists("img/{$uid}.jpg")) ?
"img/{$uid}.jpg" : "img/default.jpg" ;
}
return $tweet;
}
You're using the variable $tweet in the wrong way in your loop.
The following line will add a new element to the array $tweet:
$tweet[] = $row;
And the following line updates the element called "profile_img" in your $tweet array:
$tweet['profile_img'] = "...";
But I think, what you want is something like this:
while(($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
// Update the value for profile_img in the row
$row['profile_img'] = file_exists("img/{$uid}.jpg") ? "img/{$uid}.jpg" : "img/default.jpg" ;
// Add the manipulated row to the $tweet-array
$tweet[] = $row;
}
Please test using a debugger like xdebug (maybe a bit complicated to set up if you're not familiar with PHP) or just use var_dump();. You would've found that out pretty soon ...

Check whether value exist in database

What's the best way to check whether the value is in the database?
Am I doing it correct?
$result = mysql_query("SELECT COUNT(*) FROM table WHERE name = 'John'");
$count = count($result);
you could use straight forward ,
mysql_num_rows() ;
eg :
$con = mysql_connect($host,$uname,$passwd)
mysql_select_db($dbase,$con);
$result = mysql_query($query,$con);// query : SELECT * FROM table WHERE name='jhon';
if( ! mysql_num_rows($result)) {
echo " Sorry no such value ";
}
Yes you are doing it right, if you are only concerned with checking if there are any records where name='john'
SELECT COUNT(*) FROM table WHERE name = 'John'
will return the no. of records where name field is 'John'. if there are no records then it will return 0, and if there are any records it will return the number of records.
But the above query will miss the entries where name is 'John Abraham' or 'V john', to include even these
you can modify your query like this.
SELECT COUNT(*) FROM table WHERE name like '%John%'
I'd say yes.
$result = mysql_query("SELECT COUNT(*) AS 'nb' FROM table WHERE name = 'John'");
$line = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $line['nb'];
Will give you the number of matching rows.
$result = mysql_query("SELECT COUNT(*) as user FROM table WHERE name = 'John'");
$line = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $line['user'];
if($count!=0)
{
echo "user exists";
}
else
{
echo "There is no such user";
}

Wordpress list results from wp_users and wp_usermeta

I am writing a plugin which grabs an array of data from the wordpress database using...
$data = $wpdb->get_results("SELECT * FROM $wpdb->users", ARRAY_A);
This works fine and I can display all the info from the users table, the issue I have is that I need to also pull out the First name and Last name which are in the wp_usermeta table.
Is there a way to modify the statement to also pull those details from the other table?
Not in one query and not necessarily the slickest either, but the following will produce what you want:
$data = $wpdb->get_results("SELECT * FROM $wpdb->users", ARRAY_A);
$i = 0;
foreach($data as $single) {
$meta = $wpdb->get_results(
"SELECT meta_value
FROM $wpdb->usermeta
WHERE user_id = $single[ID]
AND (meta_key = 'first_name' OR meta_key = 'last_name')
ORDER BY meta_key",
ARRAY_A
);
$data[$i]['first_name'] = $meta[0]['meta_value'];
$data[$i]['last_name'] = $meta[1]['meta_value'];
$i++;
}
EDIT: Here it is in one query:
$data = $wpdb->get_results(
"SELECT $wpdb->users.*,
GROUP_CONCAT(
$wpdb->usermeta.meta_value
ORDER BY $wpdb->usermeta.meta_key
SEPARATOR ' '
) AS name
FROM $wpdb->users
LEFT JOIN $wpdb->usermeta
ON $wpdb->users.ID = $wpdb->usermeta.user_id
WHERE ($wpdb->usermeta.meta_key = 'first_name'
OR $wpdb->usermeta.meta_key = 'last_name')
GROUP BY $wpdb->users.ID",
ARRAY_A
);
Note that opposed to the first version, the latter does not produce $data[x]['first_name'] and $data[x]['last_name'], but $data[x]['name'] instead. This is due to either being stored in the "meta_value" column. It is not possible to accomplish your task in one query and store the first and last name in two different array keys at the same time.
Hence, if doing it the second way, you'd have to use php's explode() function later on to access the name. Or correct it in a loop after the query has been run:
$i = 0;
foreach($data as $single) {
$name_parts = explode(' ', $single['name']);
$data[$i]['first_name'] = $name_parts[0];
$data[$i]['last_name'] = $name_parts[1];
$i++;
}