I have wp_places custom table and I am getting this when I am printing array:
[0] => stdClass Object
(
[home_location] => 24
)
[1] => stdClass Object
(
[home_location] => 29
)
Now I want to implode value like this way (24,29) but in my code I am getting this error:
<b>Warning</b>: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
My Code
$getGroupType = $_POST['parent_category'];
$result = $wpdb->get_results( "SELECT home_location FROM wp_places WHERE blood_group LIKE '".$getGroupType."%'" );
$bgroup = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bgroup[] = implode(',',$row);
}
echo implode(',',$bgroup);
Any ideas or suggestions? Thanks.
$wpdb->get_results() already do the fetching for you, you don't need to call mysql_fetch_array
Given what you want to do, your code should look like this :
$getGroupType = $_POST['parent_category'];
$result = $wpdb->get_results( "SELECT home_location FROM wp_places WHERE blood_group LIKE '".$getGroupType."%'" );
$bgroup = Array();
foreach ($result as $location) {
$bgroup[] = $location->home_location;
}
echo '('.implode(',',$bgroup).')';
It's an PHP object that contains results, it isn't a MySQL Result.
Looking at the docs, it should be used like
foreach ($result as $row) {
$bgroup[] = $row->home_location;
}
echo implode(',',$bgroup)
Related
I'm having trouble processing the returned results from a DB SQL Mapper into a recognizable json encoded array.
function apiCheckSupplyId() {
/*refer to the model Xrefs*/
$supply_id = $this->f3->get('GET.supply_id');
$xref = new Xrefs($this->tongpodb);
$supply = $xref->getBySupplyId( $supply_id );
if ( count( $supply ) == 0 ) {
$this->logger->write('no xref found for supply_id=' .$supply_id);
$supply = array( array('id'=>0) );
echo json_encode( $supply );
} else {
$json = array();
foreach ($supply as $row){
$item = array();
foreach($row as $key => $value){
$item[$key] = $value;
}
array_push($json, $item);
}
$this->logger->write('xref found for supply_id=' .$supply_id.json_encode( $json ) );
echo json_encode( $json );
}
}
This is the method I am using but it seems very clunky to me. Is there a better way?
Assuming the getBySupplyId returns an array of Xref mappers, you could simplify the whole thing like this:
function apiCheckSupplyId() {
$supply_id = $this->f3->get('GET.supply_id');
$xref = new Xrefs($this->tongpodb);
$xrefs = $xref->getBySupplyId($supply_id);
echo json_encode(array_map([$xref,'cast'],$xrefs));
$this->logger->write(sprintf('%d xrefs found for supply_id=%d',count($xrefs),$supply_id));
}
Explanation:
The $xrefs variable contains an array of mappers. Each mapper being an object, you have to cast it to an array before encoding it to JSON. This can be done in one line by mapping the $xref->cast() method to each record: array_map([$xref,'cast'],$xrefs).
If you're not confident with that syntax, you can loop through each record and cast it:
$cast=[];
foreach ($xrefs as $x)
$cast[]=$x->cast();
echo json_encode($cast);
The result is the same.
The advantage of using cast() other just reading each value (as you're doing in your original script) is that it includes virtual fields as well.
I have the following code for exporting all the items in one of my pods to json. The thing is I don't need all the 130 columns in the json file, but only about 20. Since this will be done for about 150 items I thought I could save some loading time by not printing out all the fields, but I do not know how to do this. For example I only want to print the column value named 'title' for all items in the pod. My code is attached bellow.
<?php
$pods = pods('name', array('orderby' => 'name asc', 'limit' => -1));
$all_companies = $pods->export_data();
if ( !empty( $all_companies ) ) {
die(json_encode($all_companies);
}else{
die(json_encode(array('error' => 'No cars found.')));
}
?>
I thought about doing something like this:
if ( 0 < $all_companies->total() ) {
while ($all_companies->fetch()) {
$json .= $all_companies->field('title');
}
$json = rtrim($json, ",");
$json .= '}}';
}
echo $json;
But it doesn't work and also the code becomes very long.
I'd make an array of the names of the twenty fields you want then build an array of those fields for each item, by doing a foreach of those field names passed to Pods::field() inside the while loop. Like this:
$pods = pods('name', array('orderby' => 'name asc', 'limit' => -1));
$fields = array( 'field_1', 'field_2' );
if ( $pods->total() > 0 ) {
while ( $pods->fetch() ) {
foreach ( $fields as $field ) {
$json[ $pods->id() ] = $pods->field( $field );
}
}
$json = json_encode( $json );
}
Alternatively, you could hack the /pods/<pod> endpoint of our JSON API to accept a list of fields to return as the body of the request. Wouldn't be hard to do, make sure to submit a pull request if you make it work.
I need to get a list of the courses in moodle and count their respective sections as the number of topics and display in the form
[{"id":"1","name":"mathematics","topic_count":"20"},
{"id":"3","name":"Geography","topic_count":"5"},].
I tried the following
//initialize an array to hold the results
$result = array("id" =>0,"name" =>" ","topic_count" =>0);
$list = "[";
$courses = $DB->get_records_sql("SELECT id,shortname FROM mdl_course WHERE id >?",array(1)) or die ("Error in executing query 1");
foreach ($courses as $course){
$id = $course->id;
$null = "NULL";
$count = $DB->get_records_select("course_sections","course = ? AND name <> ?",array("course" =>$id, "name" => $null)) or die ("Error in executing query 2");
$result["id"] = $course->id;
$result["name"] = $course->shortname;
$result["topic_count"]= sizeof($count);
//append to list
$list .='{"id":"'.$result['id'].'","name":"'.$result['name'].'","topic_count":"'.$result['topic_count'].'"},';
}
$list .="]";
echo $list;
With this code I get the output
"Error in executing query 2"
But when instead of the $id I put a specific number say 2 I get the expected result with a constant count of sections (for course = 2 of course). Please help me out maybe I'm missing a very small point! I tried the get_records_sql but didn't work.
You are using an associative array for query 2
Either use
$count = $DB->get_records_select("course_sections","course = ? AND name <> ?",array($id, $null)) or die ("Error in executing query 2");
or
$count = $DB->get_records_select("course_sections","course = :course AND name <> :name",array("course" =>$id, "name" => $null)) or die ("Error in executing query 2");
UPDATE:
You can also use this to count the records
$DB->count_records_select('course_sections', "course = :course AND name <> :name",array("course" =>$id, "name" => $null));
http://docs.moodle.org/dev/Data_manipulation_API#Seeing_how_many_records_match_a_given_criterion
In SQL you check for NULL values with 'IS NOT NULL', rather than '<> "NULL"'.
You might also find it a lot safer to generate an array of objects, then use the function 'json_encode' to generate the final output.
e.g.
$list = array();
foreach ($courses as $course) {
$info = new stdClass();
$info->id = $course->id;
$info->name = $course->shortname;
$info->topic_count = $DB->count_records_select('course_sections', 'course = ? AND name IS NOT NULL', array($course->id));
$list[] = $info;
}
echo json_encode($list);
try this code.
you can change the $condition as you want.
it helps.
global $DB;
$table = 'course';
$condition = 'visible= "1" AND id!= "1" '; //is put into the where clause
$courses = $DB->get_records_select($table,$condition);
foreach($courses as $course){
echo '
'.$course->id.' '.userdate($course->startdate).' '.$course->fullname.' '.$course->summary.'
';
}
Please help to create a query!
This is a working example of my query Retrieve data as JSON using PHP:
<?php
$con = mysql_connect("localhost","user","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("admin_accounting", $con);
$result = mysql_query("SELECT unix_timestamp(date), sum(ksi2k) FROM accounting where lhc_vo like 'ops' group by year(date), month(date)");
$rows = array();
$rows['type'] = 'area';
$rows['name'] = 'Ops';
while($r = mysql_fetch_array($result)) {
$rows['data'][] = $r[0]*1000;
$rows['data'][] = $r[1];
array_push($rows);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
The JSON results look like this:
{"type":"area","name":"Ops","data":[1167664515000,0,1170342915000,0,1172762115000,0,1175436915000,0,1178028915000,0]}
But I need the JSON results should look like this:
{"type":"area","name":"Ops","data":[[1167664515000,0],[1170342915000,0],[1172762115000,0],[1175436915000,0],[1178028915000,0]]}
I would be very grateful for the help
while($r = mysql_fetch_array($result)) {
$rows['data'][] = array($r[0]*1000, $r[1]);
}
In addition to my other answer, you ought to consider switching away from the ancient (and now deprecated, as of PHP v5.5) ext/mysql. Here is an example using PDO, in which you can see how simple your problem becomes:
<?php
$con = new PDO(
'mysql:hostname=localhost;dbname=admin_accounting',
'user',
'password'
);
$result = $con->query('
SELECT 1000*UNIX_TIMESTAMP(date), SUM(ksi2k)
FROM accounting
WHERE lhc_vo LIKE "ops"
GROUP BY YEAR(date), MONTH(date)
');
print json_encode([
'type' => 'area',
'name' => 'Ops',
'data' => $result->fetchAll(PDO::FETCH_NUM)
]);
?>
Note that:
I have moved the multiplication into the database layer in order that I can simply call fetchAll() to obtain the resulting array;
MySQL will select an indeterminate value from amongst those in each group for the first column in the resultset; should this be undesirable, you will need to apply a suitable aggregate function to the reference to the date column; and
I have used the short array syntax, which is only available from PHP v5.4—if you're using an earlier version, you will need to replace the [ … ] of the argument to json_encode() with array( … ).
I am a newbie in Drupal, I have a table in a drupal database. I wanted to query all the content of it and display in a tabular format. Whenever I execute the query the link directs me to the blank page and nothing appears. I have attached the PhP code for the reference. Any help will be highly appreciated.
<?php
$header = array('Name', 'Age', 'Sex','University');
$rows = array();
$sql = 'SELECT Name, Age, Sex,University FROM {data_pulling} ORDER BY Name';
$res = db_query($sql);
while ($row = db_fetch_array($res)) {
$rows[] = $row;
}
print theme('table', $header, $rows);
?>
At a guess you're using Drupal 7 but are trying to use API functions from Drupal 6.
Try this
foreach ($res as $row) {
$rows[] = (array) $row;
}
print theme('table', array('rows' => $rows, 'header' => $header));
Have a look at the docs for db_query and theme_table for more information