mysqli_free_result - select successful, but still getting warning - mysql

I have a problem whereby I am running a SELECT query that returns a valid result set. I process the results using mysqli_fetch_assoc and then pass the result set to mysqli_free_result, which returns false. I have done a var_dump of the result before and after the call to confirm it is a valid result (seems to be to me - I can access the data I expect to). The query I am running is something like:
select us.user_session_key
, u.user_key
, ut.code as user_type
from t_user u
inner join t_user_type ut on u.user_type_key = ut.user_type_key
inner join t_user_session us
on u.user_key = us.user_key
where u.email = 'tim.super#en.com'
and us.session_id = 'mjsvu6fru3dtfk1bbs59fc8t20'
and us.expired_yn = 'N'
order by 1 desc
Var dump of the result object:
object(mysqli_result)#2 (5) {
["current_field"]=>
int(0)
["field_count"]=>
int(3)
["lengths"]=>
NULL
["num_rows"]=>
int(1)
["type"]=>
int(0)
}
I am using similar to the following code to process query/result:
$result = mysqli_query ( $conn, $sql );
if ($result) {
var_dump($result);
if (preg_match('/^[[:space:]]*select/i', $sql) == 1) {
while ($row = mysqli_fetch_assoc ( $result )) {
$return_val[sizeof($return_val)] = $row;
}
if (!clear_results($result)) {
print "error: ".$sql;
}
}
} else {
http_response_code(401);
print $sql . "\n";
print mysqli_error($conn);
die("error");
}
function clear_results($result) {
global $conn;
if ($result) {
if (!mysqli_free_result ( $result )) {
return false;
}
}
while (mysqli_more_results($conn)) {
mysqli_next_result($conn);
mysqli_free_result(mysqli_store_result($conn));
}
return true;
}

Related

Perl Update array

I am getting data back from a database query but I need to update an array.
sub get_query_data{
my ($self, $user_id) = #_;
my $sql_query = "Select * from table";
my ( $returndata ) = $self->_exec_and_fetch_all( $sql );
for ( #$returndata ) {
push( #$_, 'replace me' );
}
return $returndata;
}
How do I replace the third element when I am looping through the data?
There is data coming back from the query but he above is not working.
If $self->_exec_and_fetch_all can return undef,
my $rows = $self->_exec_and_fetch_all($sql);
if ($rows) {
for my $row (#$rows) {
$row->[2] = 'replaceme';
}
}
return $rows;
Otherwise,
my $rows = $self->_exec_and_fetch_all($sql);
for my $row (#$rows) {
$row->[2] = 'replaceme';
}
return $rows;
or
my $rows = $self->_exec_and_fetch_all($sql);
$_->[2] = 'replaceme' for #$rows;
return $rows;

Long query put into a CI function become not work

Does anyone can help me,I have mysql query and i have test it in phpmyadmin:
select items.name, items.category, items.supplier_id, items.item_number,
items.product_id, items.description, items.size, items.tax_included,
items.cost_price, if(items_tier_prices.unit_price is not null,
items_tier_prices.unit_price,items.unit_price) as unit_price,
items.promo_price, items.start_date, items.end_date, items.reorder_level,
items.item_id, items.allow_alt_description, items.is_serialized,
items.image_id, items.override_default_tax, items.is_service, items.deleted
from items, item_kit_items_formula
left join items_tier_prices
on items_tier_prices.item_id=item_kit_items_formula.item_id
left join price_tiers
on price_tiers.id=items_tier_prices.tier_id
where item_kit_items_formula.item_id=items.item_id
and item_kit_items_formula.item_kit_id=1
and (price_tiers.name is null or price_tiers.name like '%Jendela Kaca Mati Single%')
Query above display results just like i want. But when i put into a model function (that just work before with simple query), program dont works.
function get_info3($item_id)
{
$this->db->select('items.name, items.category, items.supplier_id, items.item_number, items.product_id, items.description, items.size, items.tax_included, items.cost_price, if(items_tier_prices.unit_price is not null, items_tier_prices.unit_price,items.unit_price) as unit_price, items.promo_price, items.start_date, items.end_date, items.reorder_level, items.item_id, items.allow_alt_description, items.is_serialized, items.image_id, items.override_default_tax, items.is_service, items.deleted ');
$this->db->from('items, item_kit_items_formula');
$this->db->join('items_tier_prices','items_tier_prices.item_id=item_kit_items_formula.item_id','left');
$this->db->join('price_tiers','price_tiers.id=items_tier_prices.tier_id','left');
$this->db->where('item_kit_items_formula.item_id=items.item_id');
$this->db->where('item_id',$item_id);
$this->db->where('(price_tiers.name IS NULL or price_tiers.name like "%jendela kaca mati single%"');
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
$item_obj=new stdClass();
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$item_obj->$field='';
}
return $item_obj;
}
}
my previous code that work is:
function get_info($item_id)
{
$this->db->from('items');
$this->db->where('item_id',$item_id);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$item_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$item_obj->$field='';
}
return $item_obj;
}
}
Can anyone help me to look at this CI function? what i have done wrong?
Thanks you guys!
function get_info3($item_id)
{
$this->db->select('i.*,i_t_p.*,i_k_i_f.*,pt.*,if(i_t_p.unit_price is not null, i_t_p.unit_price,i.unit_price) as unit_price');
$this->db->from('items as i');
$this->db->join('items_tier_prices as i_t_p','i_t_p.item_id=i_k_i_f.item_id','left');
$this->db->join('price_tiers as pt','pt.id=i_t_p.tier_id','left');
$this->db->where('i_k_i_f.item_id=i.item_id');
$this->db->where('i.item_id',$item_id);
$this->db->where('(pt.name IS NULL or pt.name like "%jendela kaca mati single%"');
}
you have to join table , i try to reduce your code but i don't know this item_kit_items_formula table is where to join with which id so you have to join this too ..hope this would help ..
I edited in my code,
try this:
function get_info3($item_id)
{
$sql_query = "select items.name, items.category, items.supplier_id, items.item_number,
items.product_id, items.description, items.size, items.tax_included,
items.cost_price, if(items_tier_prices.unit_price is not null,
items_tier_prices.unit_price,items.unit_price) as unit_price,
items.promo_price, items.start_date, items.end_date, items.reorder_level,
items.item_id, items.allow_alt_description, items.is_serialized,
items.image_id, items.override_default_tax, items.is_service, items.deleted
from items, item_kit_items_formula
left join items_tier_prices
on items_tier_prices.item_id=item_kit_items_formula.item_id
left join price_tiers
on price_tiers.id=items_tier_prices.tier_id
where item_kit_items_formula.item_id=items.item_id
and item_kit_items_formula.item_kit_id=1
and (price_tiers.name is null or price_tiers.name like '%Jendela Kaca Mati Single%')";
$query = $this->db->query($sql_query);
if($query->num_rows()==1)
{
return $query->row();
}
else
{
$item_obj=new stdClass();
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$item_obj->$field='';
}
return $item_obj;
}
}

Database Query - Order by two values (Nested Order)

I want to order results by two database values: rating_full followed by rating_count
Currently, Im ordering by the highest rating_full. it works fine.
$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON ({$wpdb->posts}.ID = rating.post_id AND rating.meta_key IN ('rating_full'))";
…
…
$sql = "cast(rating.meta_value as decimal(10,2)) {$order}";
……
The first line of code, part of the SELECT statement, retrieves the rating_full part
The second line of code is the ORDER BY part, which currently just uses the rating_count
As far as I can tell rating.meta_value referred to in the second line of code is the rating_full value
I'm trying to get it to ORDER BY rating_full, rating_count
I'm not sure how to modify the first line so that I can achieve this.
Thanks
FULL CODE:
<?php
// Sorting
add_filter('posts_join', 'directorySortingJoin',10,2);
function directorySortingJoin($join, $query) {
global $wpdb, $aThemeOptions;
if ($query->is_main_query() && !$query->is_admin && ((isset($_GET['dir-search'])) || (isset($query->query_vars["a-dir-item-category"])) || (isset($query->query_vars["a-dir-item-location"])))) {
$sql = "";
// default ordering
$orderby = (isset($aThemeOptions->directory->defaultOrderby)) ? $aThemeOptions->directory->defaultOrderby : 'post_date';
// get from get parameters
if (!empty($_GET['orderby'])) {
$orderby = $_GET['orderby'];
}
if ($orderby == 'rating') {
$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON ({$wpdb->posts}.ID = rating.post_id AND rating.meta_key IN ('rating_full'))";
//$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON (wp_posts.ID = rating.post_id AND rating.meta_key IN ('rating_full')) LEFT JOIN {$wpdb->postmeta} count ON ({$wpdb->posts} = count.post_id AND count.meta_key IN ('rating_count'))";
}
if ($orderby == 'packages') {
directorySaveUserPackagesToDb();
$sql .= " LEFT JOIN {$wpdb->usermeta} packages ON ({$wpdb->posts}.post_author = packages.user_id AND packages.meta_key IN ('dir_package'))";
}
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql .= " LEFT JOIN {$wpdb->postmeta} featured ON ({$wpdb->posts}.ID = featured.post_id AND featured.meta_key IN ('dir_featured'))";
}
$join .= $sql;
//echo $join;
}
return $join;
}
add_filter('posts_orderby', 'directorySortingOrderby',10,2);
function directorySortingOrderby($orderby, $query) {
global $wpdb, $aThemeOptions;
if ($query->is_main_query() && !$query->is_admin && ((isset($_GET['dir-search'])) || (isset($query->query_vars["a-dir-item-category"])) || (isset($query->query_vars["a-dir-item-location"])))) {
$sql = "";
// default ordering
$orderby = (isset($aThemeOptions->directory->defaultOrderby)) ? $aThemeOptions->directory->defaultOrderby : 'post_date';
$order = (isset($aThemeOptions->directory->defaultOrder)) ? $aThemeOptions->directory->defaultOrder : 'DESC';
// get from get parameters
if (!empty($_GET['orderby'])) {
$orderby = $_GET['orderby'];
}
if (!empty($_GET['order'])) {
$order = $_GET['order'];
}
if ($orderby == 'rating') {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, convert(rating.meta_value, decimal) {$order}";
} else {
//$sql = "convert(rating.meta_value, decimal) {$order}";
$sql = "cast(rating.meta_value as decimal(10,2)) {$order}";
//$sql = "cast(rating.meta_value as decimal(10,2)) {$order}, count.meta_value {$order}";
}
} else if ($orderby == 'packages') {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, packages.meta_value {$order}";
} else {
$sql = "packages.meta_value {$order}";
}
} else {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, {$wpdb->posts}.{$orderby} {$order}";
}
}
$orderby = $sql;
//echo $orderby;
}
return $orderby;
}
// Save directory packages for sorting
function directorySaveUserPackagesToDb() {
$users = get_users();
// capabilities list
$roles = array(
'administrator' => 10,
'directory_5' => 9,
'directory_4' => 8,
'directory_3' => 7,
'directory_2' => 6,
'directory_1' => 5,
'editor' => 4,
'author' => 3,
'contributor' => 2,
'subscriber' => 1
);
foreach ($users as $user) {
if (isset($user->roles[0])) {
if (array_key_exists($user->roles[0], $roles)) {
update_user_meta($user->ID, 'dir_package', $roles[$user->roles[0]]);
} else {
update_user_meta($user->ID, 'dir_package', 0);
}
}
}
}
The MySQL documentation for ORDER BY should be helpful here, particularly the last paragraph on sorting multiple columns.
Your ORDER BY should be something like
ORDER BY rating_full DESC, rating_count DESC

query with parentheses in zend framework 2.2

I want my query like this:
SELECT tbl_bids. * , tbl_department.vDeptName, tbl_user.vFirst
FROM tbl_bids
LEFT JOIN tbl_bids_department ON tbl_bids_department.iBidID = tbl_bids.iBidID
LEFT JOIN tbl_department ON tbl_department.iDepartmentID = tbl_bids_department.iDepartmentID
LEFT JOIN tbl_user ON tbl_user.iUserID = tbl_bids.iUserID
WHERE tbl_user.iUserID = '1' // with parantheses in where clause
AND (
tbl_department.vDeptName = 'PHP'
OR tbl_department.vDeptName = 'android'
)
GROUP BY tbl_bids.iBidID
ORDER BY iBidID DESC
LIMIT 0 , 30
But i can't find the way to get parantheses in my query,there are mutiple condition and loop will be there to make where clause..
here is my code
$select = $this->tableGateway->getSql()->select();
$select->columns(array('*'))
->join('tbl_bids_department', 'tbl_bids_department.iBidID = tbl_bids.iBidID', array(),"LEFT")
->join('tbl_department', 'tbl_department.iDepartmentID = tbl_bids_department.iDepartmentID',array(tbl_department.vDeptName),"LEFT")
->join('tbl_user', 'tbl_user.iUserID = tbl_bids.iUserID',array(tbl_user),"LEFT")
->group('tbl_bids.iBidID');
$where = new \Zend\Db\Sql\Where();
$where->equalTo( 'tbl_bids.eDeleted', '0' );
$sWhere = new \Zend\Db\Sql\Where();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if (isset($data['sSearch_'.$i]) && $data['sSearch_'.$i] != "")
{
if($aColumns[$i] == 'vDeptName'){
$allDept = explode(',', $data['sSearch_'.$i]);
foreach ($allDept as $key => $value) {
if($key == 0)
$sWhere->AND->equalTo("tbl_department.vDeptName", $value);
else
$sWhere->OR->equalTo("tbl_department.vDeptName", $value);
}
}elseif($aColumns[$i] == 'vFirst')
$sWhere->AND->equalTo("tbl_user.iUserID",$data['sSearch_'.$i]);
else
$sWhere->AND->like("tbl_bids.".$aColumns[$i], "%" . $data['sSearch_'.$i] . "%");
$select->where($sWhere); // here my where clause is create
}
}
//var_dump($select->getSqlString());
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
I have others many fields to pass through where which also have same problem of paratheses
if there is no any condition i can use nest() and unnest() predicate , but it will show me that string is not nested error,
So pls help me to find the solution.
Pls attach example with solution.
here is a short example
$where = new Sql\Where();
$where->equalTo('col',thirdVal')
->NEST //start braket
->equalTo('col','someVal')
->OR
->equalTo('col','secondVal')
->UNNEST //close bracet
hope this will help

Mysql / PDO - Setting Variable

I'm having trouble trying to set a variable then use it in a select statement. I keep getting a "general error" and can't figure out what I'm doing wrong. Any input would be appreciate. I'm trying to set a variable using subqueries with named parameters.
$query = $dbh->prepare("Set #available = (SELECT SUM(payments) FROM payments WHERE customer = :customer) - (SELECT SUM(charges) FROM charges WHERE customer = :customer); SELECT #available");
$query->bindParam(":customer", $customer);
$query->execute();
If you want to use MySQL user variables, for some reason, you don't need multi-queries support. They (user variables) live as long as you session (connection) is open. Therefore you can do something like this
$customer = 1;
try {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SET #available = (SELECT SUM(payments) FROM payments WHERE customer = ?) -
(SELECT SUM(charges) FROM charges WHERE customer = ?)";
$query = $db->prepare($sql);
$query->execute(array($customer, $customer));
$query = $db->prepare("SELECT #available");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Exeption: " .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
var_dump($result);
Sample output:
array(1) {
[0]=>
array(1) {
["#available"]=>
string(6) "100.00"
}
}
PDO doesn't seem to offer any formalised support for multi-queries (but some support does seem to be available), but mysqli does. Neither offer support for prepared multiple statements, though.
You can use mysqli like this:
$mysqli = new mysqli('servername', 'username', 'password', 'dbname');
$query = sprintf("Set #available = (SELECT SUM(payments) FROM payments WHERE customer = %1$s)" .
" - (SELECT SUM(charges) FROM charges WHERE customer = %1$s);".
" SELECT #available",
$mysqli->real_escape_string($customer) );
// Following code lifted from PHP Manual.
// This code will read multiple results, if they're available.
// Your query only returns one.
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
The reference is here