JSON data array query - mysql

i am using jsonTable to parse the data in to the Google table and it is working fine. now i have a problem to add multiple queries at the same time and display the data only in two columns of array which is already defined. here is my code:
$data = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table = array();
$table['cols'] = array(
array('label' => 'Vehicle', 'type' => 'number'),
array('label' => 'Distance Left', 'type' => 'number')
);
$rows = array();
while ($nt = mysql_fetch_array($data))
{
$temp = array();
$temp[] = array('v' => 'Nextoilchange');
$temp[] = array('v' =>$nt['Nextoilchange']);
// insert the temp array into $rows
$rows[]['c'] = $temp;
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
my first problem is this i want to add multiple queries in $data and each query gives one result. and my next problem is i want to display the data of multiple queries in above column defined as Distance left. and in vehicle column i want to add static data like above in $temp(1st row). i have searched a lot and i am confused how to do this. Please help me i want to display the table like this:
Vehicle Distance Left
nextoilchange 500
nextfilter 300
nextcheckup 400

I'm not tested this . If not not work try something like this .
<?php
$data[1] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$data[2] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table[1]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
$table[2]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
foreach($table as $key=>$eachtable)
{
$cols = $eachtable['cols'];
while ($nt = mysql_fetch_array($newdata))
{
foreach($cols as $key1=>$each_col)
{
if($each_col['label'] == $nt) //you have match the conditions
{
$row[$key1] = $nt['yourvalue'];
}
else
{
$row[$key1] = $nt['yourvalue1'];
}
$rows[] = $row;
}
}
$table[$key]['rows'] = $rows;
}
$jsonTable = json_encode($table);

Related

I am a Laravel beginner, can anyone tell me how I can insert an array into database?

These are the values I want to insert into the database:
$name4 = $request['name4'];
$email4 = $request['email4'];
$phone = $request['phone'];
$cat = $request['cat'];
$rname = $request['rname'];
$file = $request['file'];
$ingr = $request['ingr'];
$qty = $request['qty'];
$unit = $request['unit'];
$recp = $request['recp'];
$items = array(
'ingredients' => $ingr,
'quantity' => $qty,
'unit' => $unit
);
And insert query is as follows:
DB::INSERT("insert into tbl_contest (name, email, phone, category, recp_name, file, ingredient, recp_desc)" . "values('$name4','$email4','$phone','$cat','$rname','$file','$items','$recp')");
I wanted to add $ingr, $qty and $unit into the column ingredient.
Can anyone help me?
Thanks in advance
The $items variable can not be an array, you can turn it into a json string.
$items= json_encode(array(
'ingredients' => $ingr,
'quantity' => $qty,
'unit' => $unit
));

How do i foreach mysql result as array session

I have a page were ["cart_array"] mange session to fetch total price and total quantity in the cart my problem is that am trying to foreach mysql result into ["cart_array"] as session so i can get total price and total quantity form mysql fetch result i tried:
<?php
$sqli = mysqli_query("SELECT * FROM `books` WHERE `book`='$book'");
$productCount = mysql_num_rows($sqli); // count the output amount
if($productCount 0) {
while($row = mysqli_fetch_array($sqli)){
foreach($row as $v);
}
$id = $v["item_name"];
$product_name = $v["book"];
$price = $v["quantity"];
$_SESSION["cart_array"] = array(0 => array("item_id" => $id, "quantity" => $price)); ?>
thanks in advance
$sqli = mysqli_query("SELECT * FROM `books` WHERE `book`='$book'");
$productCount = mysql_num_rows($sqli); // count the output amount
while($row = mysqli_fetch_array($sqli)){
foreach($row as $v) {
//$id = $v["item_name"]; //mybe id
$_SESSION["cart_array"][] = array(
"item_id" => $v["id"],
"quantity" => $v["quantity"],
"product_name" => $v["book"]
);
}
}
I don't now, but in your code was some loop was empty (foreach($row as $v);) and in $_SESSION["cart_array"] will be array now;

Zend Framework 2 SQL Join Issue

I am trying to use two left outer joins with Zend Framework 2's SQL classes but for some reason it is not returning one result but the other one is working fine. I've ran the actual SQL in MySQL Workbench and it returns just like I want but it is not doing it with Zend Framework. Here is my code:
Pure SQL:
SELECT groups.group_name, members.username, groups.id FROM groups
LEFT OUTER JOIN group_admins ON groups.id = group_admins.group_id
LEFT OUTER JOIN members ON group_admins.user_id = members.id
WHERE group_admins.user_id = " . parent::getUserId()['id']
This returns the result I wish, (which can be seen here: http://imgur.com/8ydmn4f)
Now, here is the Zend Framework 2 code I have in place:
$select_admins = new Select();
$select_admins->from(array(
'g' => 'groups',
))
->join(array(
'ga' => 'group_admins'
), 'g.id = ga.group_id')
->join(array(
'm' => 'members'
), 'ga.user_id = m.id', array('username'))
->where(array('ga.user_id' => parent::getUserId()['id']));
$query_group_admin = parent::$sql->getAdapter()->query(parent::$sql->buildSqlString($select_admins), Adapter::QUERY_MODE_EXECUTE);
$group_admins = array();
foreach ($query_group_admin as $group_admin) {
$group_admins[] = $group_admin;
}
// get the group members
$select = new Select();
$select->from(array(
'g' => 'group_members'
))
->join(array(
'm' => 'members'
), 'g.member_id = m.id')
->join(array(
'grp' => 'groups'
), 'g.group_id = grp.id')
->where(array(
'g.group_id' => $group_id
));
$query = parent::$sql->getAdapter()->query(parent::$sql->buildSqlString($select), Adapter::QUERY_MODE_EXECUTE);
$member_username = array();
foreach ($query as $member) {
$member_username[] = $member['username'];
}
// get the rest of the group info
$fetch = $this->gateway->select(array(
'id' => $group_id
));
$row = $fetch->current();
if (!$row) {
return false;
}
return array(
'admins' => implode(", ", $group_admins),
'members' => implode(", ", $member_username),
'info' => $row
);
Controller:
public function grouphomeAction()
{
$id = $this->params()->fromRoute('id', 0);
if (0 === $id) {
return $this->redirect()->toRoute('members/groups', array('action' => 'index'));
}
if (!$this->getGroupsService()->getGroupInformation($id)) {
return $this->redirect()->toRoute('members/groups', array('action' => 'index'));
}
return new ViewModel(array('group_info' => $this->getGroupsService()->getGroupInformation($id)));
}
However, this only shows the group name, group creator and group members but leave the group admins field empty.
Here is the print_r result of the array returned:
Array ( [admins] => [members] => jimmysole, fooboy [info] => ArrayObject Object ( [storage:ArrayObject:private] => Array ( [id] => 2 [group_name] => Tim's Group [group_creator] => timlinden [group_created_date] => 2017-01-16 17:39:56 ) ) )
If it helps, here is a screenshot as well of the page - http://imgur.com/xUQMaUu
Any help would be appreciated!
Thanks.
Basically your joins are INNER JOINS...I know....you must hate Zend right now :p . By default they are INNER JOINS so i assume that is what is wrong. SO try to specify the type of join and you should be fine. You can find more examples here: examples
$select12->from('foo')->join('zac', 'm = n', array('bar', 'baz'), Select::JOIN_OUTER);

Getting total rows using Drupal 7 Database API when using limit

I am using the Drupal 7 Database API to search my table. I am also using the paging and sorting extenders. So the problem is, how do I display the total number of records found when my query is using limit because of the pagination? Do I need to run my query that has all of the conditions TWICE? Once to get the count and another one with the limit? That seems inefficient. Here is my code for reference. I am new to the Database API so feel free to adjust my code or point me in the right direction if I'm doing something wrong. Also I'm not done with this yet and only have one condition in place, but I will end up having 3. THANKS:
function job_search() {
// Initialising output
$output = 'SOME STUFF';
// Table header
$header = array(
array('data' => 'Description'),
array('data' => 'Location', 'field' => 'job_location_display'),
array('data' => 'Specialty', 'field' => 'specialty_description'),
array('data' => 'Job Type', 'field' => 'job_board_type'),
array('data' => 'Job Number', 'field' => 'job_number'),
);
// Setting the sort conditions
if(isset($_GET['sort']) && isset($_GET['order'])) {
// Sort it Ascending or Descending?
if($_GET['sort'] == 'asc')
$sort = 'ASC';
else
$sort = 'DESC';
// Which column will be sorted
switch($_GET['order']) {
case 'Location':
$order = 'job_location_display';
break;
case 'Specialty':
$order = 'specialty_description';
break;
case 'Job Number':
$order = 'job_number';
break;
case 'Job Type':
$order = 'job_board_type';
break;
default:
$order = 'job_number';
}
}
else {
$sort = 'ASC';
$order = 'job_number';
}
// Query object
$query = db_select("jobs", "j");
// Adding fields
$query->fields('j');
if(isset($_GET['location'])) {
$query->condition('j.job_state_code', $_GET['location'], '=');
}
// Set order by
$query->orderBy($order, $sort);
// Pagination
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);
// Executing query
$result = $query->execute();
// Looping for filling the table rows
while($data = $result->fetchObject()) {
$description = '<div class="thumbnail"><img src="/sites/all/themes/zen/vista_assets/images/job_headers/' . $data->job_image_file . '"/></div>';
$description .= '<div class="title">' . $data->job_board_subtitle . '</div>';
// Adding the rows
$rows[] = array($description, $data->job_location_display, $data->specialty_description, $data->job_board_type, $data->job_number);
}
$output .= theme('pager');
// Setting the output of the field
$output .= theme_table(
array(
'header' => $header,
'rows' => $rows,
'attributes' => array('id' => array('job-listing')),
'sticky' => true,
'caption' => '',
'colgroups' => array(),
'empty' => t("No records found.")
)
).theme('pager');
// Returning the output
return $output;
}
This ended up working:
//get total records
$num_rows = $query->countQuery()->execute()->fetchField();
// add paging and sorting
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);
//execute again
$result = $query->execute();
According to the documentation:https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7
in order to get the total number of rows it is better to use db_query() function, cause it has the method rowCount() which returns total number of query rows:
<?php
// Using the same query from above...
$uid = 1;
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));
// Fetch next row as a stdClass object.
$record = $result->fetchObject();
// Fetch next row as an associative array.
$record = $result->fetchAssoc();
// Fetch data from specific column from next row
// Defaults to first column if not specified as argument
$data = $result->fetchColumn(1); // Grabs the title from the next row
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();
// Retrieve all records as stdObjects into an associative array
// keyed by the field in the result specified.
// (in this example, the title of the node)
$result->fetchAllAssoc('title');
// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// Also good to note that you can specify which two fields to use
// by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be nid => created
$result->fetchAllKeyed(1,0); // would be title => nid
// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($db_column_number);
// Count the number of rows
$result->rowCount();
?>

Zend Framework 2: LEFT JOIN issue

public function getInterests($userID) {
$result = $this->tableGateway->select(function (Select $select) use ($userID) {
$select->join('interests', 'users_interests.interest_id = interests.interest_id', array('*'), 'left');
$where = new Where();
$where->equalTo('user_id', $userID);
$select->where($where);
});
return $result;
}
Here is my method. It simply selects all records from users_interests with user_id = $userID and joins the 'interests' table. So far, so good, but when trying to display the fetched results, the fields from the joined table just do not exist. Here is the dump of the $result:
Zend\Db\ResultSet\ResultSet Object
(
[allowedReturnTypes:protected] => Array
(
[0] => arrayobject
[1] => array
)
[arrayObjectPrototype:protected] => Object\Model\UsersInterests Object
(
[settings_id] =>
[user_id] =>
[interest_id] =>
)
[returnType:protected] => arrayobject
[buffer:protected] =>
[count:protected] => 2
[dataSource:protected] => Zend\Db\Adapter\Driver\Pdo\Result Object
(
[statementMode:protected] => forward
[resource:protected] => PDOStatement Object
(
[queryString] => SELECT `users_interests`.*, `interests`.* FROM `users_interests` LEFT JOIN `interests` ON `users_interests`.`interest_id` = `interests`.`interest_id` WHERE `user_id` = :where1
)
[options:protected] =>
[currentComplete:protected] =>
[currentData:protected] =>
[position:protected] => -1
[generatedValue:protected] => 0
[rowCount:protected] => 2
)
[fieldCount:protected] => 6
[position:protected] =>
)
I badly need help on this because I am supposed to finish my project until Sunday. Thanks in advance.
You can use the following to apply left join. $select::JOIN_LEFT instead of 'left'.
public function getInterests($userID) {
$result = $this->tableGateway->select(function (Select $select) use ($userID) {
$select->join('interests', 'users_interests.interest_id = interests.interest_id', array('*'), $select::JOIN_LEFT);
$where = new Where();
$where->equalTo('user_id', $userID);
$select->where($where);
});
return $result;
}
It seems you have a problem in the WHERE clause of the join. This also shows in the error here:
[queryString] => SELECT `users_interests`.*, `interests`.* FROM `users_interests` LEFT JOIN .
`interests` ON `users_interests`.`interest_id` = `interests`.`interest_id`
WHERE `user_id` = :where1
Try this:
$select->from($this->table)
->join('interests', 'users_interests.interest_id = interests.interest_id',
array('*'), 'left');
$where = new Where();
$where->equalTo('user_id', $userID) ;
$select->where($where);
I can not follow your code completely, like here:
$this->tableGateway->select(function (Select $select) use ($userID) {
But, here is a very nice article on this. I think, you can simplify your code a little.
Have you iterated over the resultset? You can see there's two matching rows:
[rowCount:protected] => 2
You have a ResultSet object, but it will not load any of the rows until requested, they are "lazy loaded" when you iterate over the object.
You can force the resultset to get them all for you:
var_dump($resultSet->toArray()); // force load all rows
or iterate over the ResultSet:
foreach($resultset as $row) {
var_dump($row); // each row loaded on request
}
I have written about this before and maybe it will help you as well.
TableGateway with multiple FROM tables