return only column name values from mysql table - mysql

sorry but i didn't knew how to explain the question in on sentence...
actually i have code like this when i do mysql_fetch_array...
[0] => 10
[id] => 10
[1] => 58393
[iid] => 58393
[2] => 0
[ilocationid] => 0
[3] => 38389
[iapptid] => 38389
[4] => 2012-06-30T00:00:00
[ddate] => 2012-06-30T00:00:00
[5] => 1000
[ctimeofday] => 1000
but i want to return something like this
[id] => 10
[iid] => 58393
[ilocationid] => 0
[iapptid] => 38389
[ddate] => 2012-06-30T00:00:00
[ctimeofday] => 1000
i mean without the numeric representatives of the columns. how do i do it...please help...

As explained in the manual for PHP's mysql_fetch_array() function:
The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
Therefore, you want either:
mysql_fetch_array($result, MYSQL_ASSOC);
or
mysql_fetch_assoc($result);
Note however the warning:
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_fetch_array()
PDOStatement::fetch()

Related

Yii2 - QueryAll is having issue

I am using Query Builder with multiple where clause. When I use this query,
$query1 = new \yii\db\Query();
$query1->select('*')
->from('assessment_score ca')
->where(['AND','ca.is_status' => 0, 'ca.assessment_type' => 'CONTINUOUS ASSESSMENT', 'ca.ca_type' => 'CONTINUOUS ASSESSMENT'])
->andFilterWhere(['ca.state_office_id' => $model->report_state_office_id])
->andFilterWhere(['ca.study_centre_id' => $model->report_study_centre_id])
->andFilterWhere(['ca.programme_id' => $model->report_programme_id])
->andFilterWhere(['ca.department_id' => $model->report_department_id])
->andFilterWhere(['ca.academic_level_id' => $model->report_academic_level_id])
->andFilterWhere(['ca.academic_year_id' => $model->report_academic_year_id])
->andFilterWhere(['ca.academic_semester_id' => $model->report_academic_semester_id])
->andFilterWhere(['ca.course_id' => $model->report_course_id]);
$command=$query1->createCommand();
$ca_data=$command->queryAll();
I got this error
Then, when I changed the code to this, no response:
$selected_list = $_POST['ca'];
$query1 = new \yii\db\Query();
$query1->select('*')
->from('assessment_score ca')
->where(['ca.is_status' => 0])
->andWhere(['ca.assessment_type' => 'CONTINUOUS ASSESSMENT'])
->andWhere(['ca.ca_type' => 'CONTINUOUS ASSESSMENT'])
->andFilterWhere(['ca.state_office_id' => $model->report_state_office_id])
->andFilterWhere(['ca.study_centre_id' => $model->report_study_centre_id])
->andFilterWhere(['ca.programme_id' => $model->report_programme_id])
->andFilterWhere(['ca.department_id' => $model->report_department_id])
->andFilterWhere(['ca.academic_level_id' => $model->report_academic_level_id])
->andFilterWhere(['ca.academic_year_id' => $model->report_academic_year_id])
->andFilterWhere(['ca.academic_semester_id' => $model->report_academic_semester_id])
->andFilterWhere(['ca.course_id' => $model->report_course_id]);
$command=$query1->createCommand();
$ca_data=$command->queryAll();
How do I re-write the code appropriately to solve the issue of multiple where clause?
You might need to change the query format for the where() statement as you need to provide every condition (name=>value pair) as a separate array rather than just name=>value pairs, you currently have
->where(['AND', 'ca.is_status' => 0, 'ca.assessment_type' => 'CONTINUOUS ASSESSMENT', 'ca.ca_type' => 'CONTINUOUS ASSESSMENT'])
which will create the query like below if no other parameter is provided for andFilterWhere() statements.
SELECT * FROM `assessment_score` `ca`
WHERE (0)
AND (CONTINUOUS ASSESSMENT) AND (CONTINUOUS ASSESSMENT)
which is incorrect and throwing the error, you can notice that in your Exception image, so change it to the one below
->where(['AND',
['ca.is_status' => 0],
['ca.assessment_type' => 'CONTINUOUS ASSESSMENT'],
['ca.ca_type' => 'CONTINUOUS ASSESSMENT']
])
which will output the query like
SELECT * FROM `assessment_score` `ca`
WHERE (`ca`.`is_status`=0)
AND (`ca`.`assessment_type`='CONTINUOUS ASSESSMENT')
AND (`ca`.`ca_type`='CONTINUOUS ASSESSMENT')
Your complete query should look like this
$query1 = new \yii\db\Query();
$query1->select('*')
->from('assessment_score ca')
->where(['AND',
['ca.is_status' => 0],
['ca.assessment_type' => 'CONTINUOUS ASSESSMENT'],
['ca.ca_type' => 'CONTINUOUS ASSESSMENT']
])
->andFilterWhere(['ca.state_office_id' => $model->report_state_office_id])
->andFilterWhere(['ca.study_centre_id' => $model->report_study_centre_id])
->andFilterWhere(['ca.programme_id' => $model->report_programme_id])
->andFilterWhere(['ca.department_id' => $model->report_department_id])
->andFilterWhere(['ca.academic_level_id' => $model->report_academic_level_id])
->andFilterWhere(['ca.academic_year_id' => $model->report_academic_year_id])
->andFilterWhere(['ca.academic_semester_id' => $model->report_academic_semester_id])
->andFilterWhere(['ca.course_id' => $model->report_course_id]);
$command = $query1->createCommand();
$ca_data = $command->queryAll();
based on yii2 guide for Operator Format
Operator format allows you to specify arbitrary conditions in a
programmatic way. It takes the following format:
[operator, operand1, operand2, ...] where the operands can each be
specified in string format, hash format or operator format
recursively, while the operator can be one of the following:
and: the operands should be concatenated together using AND. For
example, ['and', 'id=1', 'id=2']
so in your case should be
->where(['AND', 'ca.is_status = 0',
"ca.assessment_type = 'CONTINUOUS ASSESSMENT'",
"ca.ca_type = 'CONTINUOUS ASSESSMENT'"])
https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder#operator-format
All you need is to remove AND from array passed to where():
->where([
'ca.is_status' => 0,
'ca.assessment_type' => 'CONTINUOUS ASSESSMENT',
'ca.ca_type' => 'CONTINUOUS ASSESSMENT'
])
If you pass associative array, it will be treated as pairs of column-value for conditions for WHERE in query. If you pass AND as first element, it is no longer a associative array, and query builder will ignore keys and only combine values as complete condition.

MySql query in cake php Api

for data retrieval i need to use binary keyword for case sensitive search in mysql
this is the query i want to make
SELECT username FROM users
WHERE BINARY first_name LIKE 'eph%'
OR BINARY last_name LIKE 'eph%'
OR BINARY username LIKE 'eph%'
and this is the query i have made in cakephp without binary
$this->User->find('list', array(
'fields' => array('User.username'),
'conditions' => array("OR" =>
array("BINARY User.last_name LIKE" => $search_data."%","BINARY User.username LIKE" => $search_data."%",
"BINARY User.first_name LIKE" => $search_data."%"))
));
can any 1 help me out making the binary query using cakephp api ....
Ok ... you were almost there. You only need to put the Field in a bracket to tell CakePHP not to deal with the BINARY keyword as a field name
Believe this should work:
$this->User->find('list', array(
'fields' => array('User.username'),
'conditions' => array(
"OR" =>array(
"BINARY (`User`.`last_name`) LIKE" => $search_data."%",
"BINARY (`User`.`username`) LIKE" => $search_data."%",
"BINARY (`User`.`first_name`) LIKE" => $search_data."%"))
));

Appending one array to another array in the same loop

This is for a custom Wordpress page but I think the basic array principles should apply. I've not worked with complex arrays before so am a little lost, trial and error hasn't worked yet.
I have a database of Posts, each post has meta_key's of 'shop' and 'expired'.
'expired' is a date (YYYY-MM-DD) which is used to tell the visitor when a Post's content expires and this key is what I'm trying to work with.
If a Post's 'expired' date is before today, they are shown 'Offer expired'
If the 'expired' date is in the future, they are shown 'Offer expires in X days' (this script isn't shown below, not necessary)
Posts are listed in order of their 'expired' date, ASC. The problem is that when a post expires I'd like that post to show at the end rather than stay on top.
Example of what I currently see:
Post 1 | Expired 3 days ago
Post 2 | Expired 1 day ago
Post 3 | Expires in 2 days
Post 4 | Expires in 6 days
And what I'd like to see (note Post X order):
Post 3 | Expires in 2 days
Post 4 | Expires in 6 days
Post 2 | Expired 1 day ago
Post 1 | Expired 3 days ago
This is my array code where I've attempted to merge the two
$postid = get_the_ID();
$meta1 = get_post_meta($postid, 'shop', true);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$today = date('Y-m-d', time());
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'shop',
'value' => $meta1
)
),
'paged' => $paged,
'posts_per_page' => '5',
'meta_key' => 'expired',
'meta_value' => $today,
'meta_compare' => '>',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$args2 = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'shop',
'value' => $meta1
)
),
'meta_key' => 'expired',
'meta_value' => $today,
'meta_compare' => '<',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$final = $args + $args2;
$query = new WP_Query( $final );
while ( $query->have_posts() ) : $query->the_post(); ?>
HTML FOR DISPLAYING POST
endwhile;
At the moment it doesn't seem to take any notice of "$args2" and only displays $args
I'm sure my idea is on the right lines, needing to create two arrays and join them with the "+" rather than array_merge() but that's where I can't get any further.
Can someone kindly shed some light please? Thanks!
Now the solution you are trying to achieve is actually impossible if i understood your requirement properly. Let me explain why this is not achievable.
In your two arrays $args and $args2 most of the values are same leaving two odds , i am picking only one to just illustrate :
//it's in args
'meta_compare' => '>'
//it's in args2
'meta_compare' => '<'
Now what happens when you are trying to merge this two using array_merge($args , $args2):
'meta_compare' => '<'
That means it is taking 'meta_compare' from the later array which is $args2 here. This is the behavior of array_merge function defined in the doc:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one
Now if you are using + array union operator $args+$args2 :
'meta_compare' => '>'
That means it is taking 'meta_compare' from the first array which is $args here. This is the behavior of + array union operator defined in the doc :
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
Why it is happening because in the same level keys have to be unique . So in your situation they are in the same level :
$args = array ('key' => 'value1')
$args2= array ('key' => 'value2')
So only and only one value can exist here as in the merged array 'key' can point only one.
If this was the scenario :
$args [0] = array ('key' => 'value1' )
$args2 [1]= array ('key' => 'value2' )
Then both of the value stored by key will be resrved. This will be the resulting array :
array(2) {
[0]=>
array(1) {
["key"]=>
string(6) "value1"
}
[1]=>
array(1) {
["key"]=>
string(6) "value2"
}
}
Though i am not a geek of WP but as far as i understood from WP_query you can't pass args like this (I am not sure). So that leaves only one way to achieve this. You can pass these two args separately and merge the result as the result most probably (I am not sure) will be a 2D array you can merge them easily.
Hope that helps.
Happy coding :)
You can't just add 2 arrays together using the args+args2 syntax. PHP has no way of knowing what you mean by that. If you want the result to be an array containing both of these arrays, you could do this:
$final = array($args, $args2)
Otherwise I'm not sure how you want these two arrays combined. If you clarify how they need to be combined we might be able to help more.

PHP don't generate properly array from database (UBUNTU)

I have a little problem.
There are two tables in my database: users and classes. The first one contains info about users, and the second one - about user classes and about access rights.
Now I'm extracting all data from there using this:
SELECT * FROM users NATURAL JOIN classes WHERE users.ID_User = '$id';
The mysql code works and returns a right array.
Now, when I'm doing next:
<?php
$result = mysql_query($sql_above);
$row = mysql_fetch_array($result);
print_r($row);
?>
... i'm getting this:
Array ( [0] => 1 [ID_User] => 1 [1] => John [Name] => John [2] => Doe [Surname] => Doe [3] => ... [16] => Owner [Class] => Owner [17] => [All] => [18] => [CanAuth] => [19] => [CanViewData] => [20] => [CanAddData] => [21] => [CanAlterData] => [22] => [CanDeactivateData] => [23] => [CanDeleteData] => [24] => [CanMgLocatari] => ... )
Columns from 17 till the end are access rights, noted in the database by 1 or 0. And there, they're missing.
Is there any option to enable in PHP configuration to correct this thing? Because on a Windows machine, the code executes properly and rights are working.
PHP Version 5.3.6-13ubuntu3.7 | Apache/2.2.20 (Ubuntu) | MySQL client version: 5.1.62
Please, reply. Thanks!

Joins - Merge result into single, multidimensional array

I'm performing a simple query that joins two tables together. What I get is something like this.
array(
[0] => array(
'id' => 52
'name' => 'charles',
'sale_id' => 921,
'sale_time' => 1306393996,
'sale_price' => 54.21
),
[1] => array(
'id' => 52
'name' => 'charles',
'sale_id' => 922,
'sale_time' => 1306395000,
'sale_price' => 32.41
),
...
);
...which is the expected result. However, I'd like the query to return something like this:
array(
[0] => array(
'id' => 52,
'name' => 'charles',
'sales' => array(
[0] => array(
'sale_id' => 921,
'sale_time' => 1306393996,
'sale_price' => 54.21
),
[1] => array(
'sale_id' => 922,
'sale_time' => 1306395000,
'sale_price' => 32.41
),
...
)
)
)
Now I realize I could simply perform two queries, one for the user info, and another for sales, and merge those arrays together using whatever language I'm using (PHP in this case). But I have many arrays of properties and querying and merging for those seems awfully inelegant to me (although it does work). It seems to me there'd be a way to work with a single, unified object without duplicating data.
Just wondering if there was a no-brainer query, or if that's simply not easy through MySQL alone.
I would say this is not possible with MySQL alone - you have to do some tricks at application level. That is, because even if you send a single query that will bring you all the data from MySQL to your application (PHP), they will come as a denormalized array of data - your first case.
If you want to get the data as in your second case, I'd recommend using some ORM - in Ruby there is ActiveRecord, in Perl there are Class::DBi, DBIx::Class and many more - I can not name one for PHP that is able to do this, but I am sure there are plenty.