Something not working as expected in this PHP function - php

I am trying to pull data from MySQL and this supposed to show complete data but this is showing only one row. This is supposed to show all rows of users. I don’t know what I did wrong:
Here is the code:
function getCashoutRequests($uid, $limit) {
if (!empty( $limit )) {
$query = mysql_query( '' . 'SELECT * FROM cashouts WHERE uid = ' . $uid . ' ORDER BY id DESC LIMIT ' . $limit );
}
else {
$query = mysql_query( '' . 'SELECT * FROM cashouts WHERE uid = ' . $uid . ' ORDER BY id DESC' );
}
if (mysql_num_rows( $query )) {
if ($row = mysql_fetch_object( $query )) {
$row->id;
$amount = $row->amount;
$status = $row->status;
$client_notes = nl2br( $row->user_notes );
$admin_notes = nl2br( $row->admin_notes );
$request_date = $row->request_date;
$payment_date = $row->payment_date;
$fee = $row->fee;
$priority = $hid = $row->priority;
$method = $row->method;
if ($payment_date != '0000-00-00 00:00:00') {
$payment_date = date( 'd M, Y', strtotime( $payment_date ) );
}
$request_date = date( 'd M, Y', strtotime( $request_date ) );
$payHistory []= array( 'id' => $hid, 'cash' => $amount, 'status' => $status, 'method' => $method, 'client_notes' => $client_notes, 'admin_notes' => $admin_notes, 'date' => $request_date, 'payment_date' => $payment_date, 'fee' => $fee, 'priority' => $priority );
}
return $payHistory;
}
return false;
}

On this line you have if:
if ($row = mysql_fetch_object( $query )) {
If you use if that would only go to the first value since if simply tests a condition once. Instead try while like this:
while ($row = mysql_fetch_object( $query )) {
As explained in the PHP manual entry for while:
The meaning of a while statement is simple. It tells PHP to execute
the nested statement(s) repeatedly, as long as the while expression
evaluates to TRUE.

Related

I'm getting what seems to be an infinite loop and can't figure out why - PHP/WordPress

I'm running through some distinct user ID's (about 147 of them, retrieved from a table with many duplicates) with a foreach loop and then when retrieved, using them to retrieve more user details. I then place these details within an array in order to push them to my JavaScript.
For some reason the result that I get from the array is what seems to be an infinite loop that has quit somewhere in the process.
Here's an example:
This is the code that I am currently running:
public function payments_rt_search() {
global $wpdb;
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$threshold = intval($_POST['threshold']);
$results = $wpdb->get_results( "SELECT DISTINCT vendor_id FROM {$wpdb->prefix}wcpv_commissions WHERE order_date BETWEEN '".$date1."' AND '".$date2."'");
$past_threshold_users = [];
// echo json_encode($results);
// wp_die();
foreach ($results as $user_R) {
$total_commissions = $wpdb->get_results( "SELECT SUM(product_commission_amount) AS TotalCommissions FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id);
$total_commission = 0;
foreach($total_commissions as $total_commission_res)
{
$total_commission = $total_commission_res->TotalCommissions;
}
if ($total_commission >= $threshold)
{
$res2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id." LIMIT 1");
// echo json_encode($res2[0]);
// wp_die();
//Add user details to array
$user_deets = $res2[0];
$user_arr = array(
'vendor_id' => $user_deets->vendor_id,
'vendor_name' => $user_deets->vendor_name,
'paypal_email' => '',
'amount' => $total_commission,
'currency' => '$',
'commission_status' => $user_deets->commission_status
);
$past_threshold_users[] = $user_arr;
// echo json_encode($user_arr);
// wp_die();
}
else
{
continue;
}
echo json_encode($past_threshold_users);
}
//echo json_encode($results);
wp_die();
}
Try this code
I have move this echo json_encode($past_threshold_users); code after foreach loop.
public function payments_rt_search() {
global $wpdb;
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$threshold = intval($_POST['threshold']);
$results = $wpdb->get_results( "SELECT DISTINCT vendor_id FROM {$wpdb->prefix}wcpv_commissions WHERE order_date BETWEEN '".$date1."' AND '".$date2."'");
$past_threshold_users = [];
// echo json_encode($results);
// wp_die();
foreach ($results as $user_R) {
$total_commissions = $wpdb->get_results( "SELECT SUM(product_commission_amount) AS TotalCommissions FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id);
$total_commission = 0;
foreach($total_commissions as $total_commission_res)
{
$total_commission = $total_commission_res->TotalCommissions;
}
if ($total_commission >= $threshold)
{
$res2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id." LIMIT 1");
// echo json_encode($res2[0]);
// wp_die();
//Add user details to array
$user_deets = $res2[0];
$user_arr = array(
'vendor_id' => $user_deets->vendor_id,
'vendor_name' => $user_deets->vendor_name,
'paypal_email' => '',
'amount' => $total_commission,
'currency' => '$',
'commission_status' => $user_deets->commission_status
);
$past_threshold_users[] = $user_arr;
// echo json_encode($user_arr);
// wp_die();
}
/*else
{
continue;
} */
}
echo json_encode($past_threshold_users);
//echo json_encode($results);
wp_die();
}

Auto increment Invoice ID in Code-igniter

i am very new to code igniter /php .
Before i was using randomly generated invoice number like
$invoice_no = rand(9999,9999999999);
But now i wanted to increment invoice number and add current year as a prefix to it . But somewhere i am doing wrong as this code failed execute . Can some one point me in the right direction .
My model is ...
function insertInvoice($data)
{
$this->db->trans_begin();
$invoice = array();
if(!empty($data['client_id']))
{
$invoice['invoice_client_id'] = $data['client_id'];
}else{
$client_data = array(
'client_name' => $data['customername'],
'client_address1' => $data['address1']
);
$this->db->insert('client_details', $client_data);
$insert_id = $this->db->insert_id();
$invoice['invoice_client_id'] = $insert_id;
}
$query = $this->db->query("SELECT * FROM invoice ORDER BY invoice_id DESC LIMIT 1");
$result = $query->result_array(0);
$result ++;
$curYear = date('Y');
$invoice_no = $curYear . '-' .$result;
$invoice['invoice_no'] = $invoice_no;
$invoice['invoice_subtotal'] = $data['subTotal'];
$invoice['invoice_tax'] = $data['tax'];
$invoice['invoice_tax_amount'] = $data['taxAmount'];
$invoice['invoice_total'] = $data['totalAftertax'];
$invoice['invoice_total_extra'] = $data['totalextra'];
$invoice['invoice_rent'] = $data['rent'];
$invoice['invoice_paid'] = $data['amountPaid'];
$invoice['invoice_due'] = $data['amountDue'];
$invoice['invoice_desc'] = $data['notes'];
$invoice['invoice_items_count'] = $data['item_count'];
$invoice['invoice_extra_count'] = $data['extra_count'];
$invoice['invoice_miscellaneous'] = $data['miscellaneous'];
$this->db->insert('invoice', $invoice);
$i=1;
do {
$items = array(
'invoice_no' => $invoice_no,
'item_name' => $data['invoice']['product_name'][$i],
'item_price' => $data['invoice']['product_price'][$i],
'item_qty' => $data['invoice']['product_qty'][$i],
'item_total' => $data['invoice']['total'][$i],
'item_noof_crate_wait' => $data['invoice']['noof_crate_wait'][$i],
'item_crate_wait' => $data['invoice']['crate_wait'][$i],
'item_choot' => $data['invoice']['choot'][$i],
'item_net_quantity' => $data['invoice']['net_qty'][$i]
);
$this->db->insert('invoice_items',$items);
$i++;
} while($i<$data['item_count']);
$j=1;
do {
$extraitems = array(
'invoice_no' => $invoice_no,
'extra_item_name' => $data['extra']['name'][$j],
'extra_item_qunatity' => $data['extra']['qty'][$j],
'extra_item_price' => $data['extra']['price'][$j],
'extra_item_total' => $data['extra']['total'][$j]
);
$this->db->insert('extra_items',$extraitems);
$j++;
} while($j<$data['extra_count']);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return FALSE;
}
else
{
$this->db->trans_commit();
return TRUE;
}
}
invoice_id is primary key in DB .
You're attempting to increment the result array but what you really need is to acquire and increment a field value.
//you only need one field so ask only for that
$query = $this->db->query("SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1");
//you really should check to make sure $query is set
// before trying to get a value from it.
//You can add that yourself
//Asked for only one row, so only retrieve one row -> and its contents
$result = $query->row()->invoice_id;
$result ++;
...
I'm guessing you're getting an "Object conversion to String error" on line $invoice_no = $curYear . '-' .$result;
Since $result contains an object and you're using it as a string. Print the $result variable to check how to use the data assigned to it.

How do I add dynamic WHERE clause for search filtering?

I have 7 search parameters although the code below shows only two, Title and Type.
We would like to give our users the ability to search by ANY of the 7 parameters.
They should also be given the ability to search by more than one parameter.
How would I adapt the code below to use a dynamic $where clause?
Example, a user could select where type='some value'.
A user should also be able to select where type='some value' and title='some value'.
Thank you in advance.
function ms_escape_string($data) {
if ( !isset($data) or empty($data) ) return '';
if ( is_numeric($data) ) return $data;
$non_displayables = array(
'/%0[0-8bcef]/', // url encoded 00-08, 11, 12, 14, 15
'/%1[0-9a-f]/', // url encoded 16-31
'/[\x00-\x08]/', // 00-08
'/\x0b/', // 11
'/\x0c/', // 12
'/[\x0e-\x1f]/' // 14-31
);
foreach ( $non_displayables as $regex )
$data = preg_replace( $regex, '', $data );
$data = str_replace("'", "''", $data );
return $data;
}
$strprojectTitle = null;
$strbidType = null;
if(isset($_POST["projectTitle"]))
{
$strprojectTitle = $_POST["projectTitle"];
}
if(isset($_POST["BidType"]))
{
$strbidType = $_POST["BidType"];
}
?>
<?php
$sql = "Select b.ID,convert(char(10),b.BidDate,101) BidDate,convert(char(10),
b.DueDate,101)DueDate,b.BidTitle,b.DueTime,b.BidID,BidIDFile,
d.Department,b.BidType,CASE WHEN b.AwardDate ='01/01/1900' Then NULL ELSe convert(char(10),b.AwardDate,101)END AS AwardDate,
convert(char(10),b.LastUpdate,101) LastUpdate,s.Status
FROM bids b inner join dept d on b.Department=d.DeptID inner join Status s on b.BidStatus=s.StatusId WHERE b.BidTitle = ' . ms_escape_string($strprojectTitle) . ' OR b.BidType = ' . ms_escape_string($strbidType) . ' ";
///****Latest attempt
$fields = array(
'projectTitle' => 'b.BidTitle',
'BidType' => 'b.BidType'
);
$where = array();
foreach($fields as $fieldPost => $fieldDb) {
if(isset($_POST[$fieldPost]) && strlen($_POST[$fieldPost]) > 0) {
$where[] = "`$fieldDb` = '$_POST[$fieldPost]'";
}
}
$sql = "Select b.ID,convert(char(10),b.BidDate,101) BidDate,convert(char(10),
b.DueDate,101)DueDate,b.BidTitle,b.DueTime,b.BidID,BidIDFile,
d.Department,b.BidType,CASE WHEN b.AwardDate ='01/01/1900' Then NULL ELSe convert(char(10),b.AwardDate,101)END AS AwardDate,
convert(char(10),b.LastUpdate,101) LastUpdate,s.Status
FROM bids b inner join dept d on b.Department=d.DeptID inner join Status s on b.BidStatus=s.StatusId
" . ( count($where) > 0 ? " WHERE " . implode(' AND ', $where) : "" );
Remove this part in your code:
$strprojectTitle = null;
$strbidType = null;
if(isset($_POST["projectTitle"]))
{
$strprojectTitle = $_POST["projectTitle"];
}
if(isset($_POST["BidType"]))
{
$strbidType = $_POST["BidType"];
}
And replace it with the one below, which enables a dynamic way of building the WHERE conditions:
## easily add here the fields you have
$fields = array(
'projectTitle' => 'b.BidTitle',
'BidType' => 'b.BidType'
);
$where = array();
foreach($fields as $fieldPost => $fieldDb) {
if(isset($_POST[$fieldPost]) && strlen($_POST[$fieldPost]) > 0) {
$where[] = "`$fieldDb` = '" . ms_escape_string($_POST[$fieldPost]) . "'";
}
}
## Use the $where array in your final SQL query
## important to test if count($where) > 0 in case no search has been made
$sql = "SELECT ..... " . ( count($where) > 0 ? " WHERE " . implode(' AND ', $where) : "" );
A more advanced example to build the WHERE string by supporting multiple search types (for example the search comparators: LIKE %..% and =)
## support multiple search comparators
$fields = array(
'projectTitle' => array('field' => 'b.BidTitle', 'searchType' => 'like'),
'BidType' => array('field' => 'b.BidType', 'searchType' => 'equal')
);
$where = array();
foreach($fields as $fieldPost => $field) {
if(isset($_POST[$fieldPost]) && strlen($_POST[$fieldPost]) > 0) {
if($field['searchType'] == 'like') {
$where[] = "`".$field['field']."` LIKE '%" . ms_escape_string($_POST[$fieldPost]) . "%'";
} else {
$where[] = "`".$field['field']."` = '" . ms_escape_string($_POST[$fieldPost]) . "'";
}
}
}

How can i show sphinx search result in PHP

How is that possible to show sphinx search result via PHP
i have installed sphinx and configured but i am unable to get the result via PHP
Check the Sphinx Library : Sphinx Documentation
The Below Code Is Used To Get The Full Content From Sphinx Search Result
Now Currently We Need To Give The Id In $SQL line
<?php
echo "Welcome To Sphinx Search Site </br>";
$q = "html";
$sphx = sphinx_search("html", 0, 20);
$sphx['122'];
$ids = 122;
$sql = "SELECT post_title , post_content FROM wp_posts WHERE ID = '122'";
db();
if( !($r = mysql_query($sql)))
die("[MYSQL]".mysql_error() . mysql_errno() );
$max = $sphx['total'];
$num_rows = $sphx['docs'];
echo "<b>Displaying {$num_rows} results of {$max}</b><br /><br />";
while($row = mysql_fetch_assoc($r) ) {
echo "{$row['post_title']} <br />{$row['post_content']}<br /><hr />";
}
mysql_free_result($r);
/*
* SPHINX Search
*/
/*
* Search sites by Keywords using sphinx; with an option to search sites tags only
* #param string $q te keyword
* #param int $i id of the first result to return
* #param int $max max results to return
* #param bollen $url set to true to return matches from the 'url' column only
*
* #return string $ids comma seperated list of ids
*/
function sphinx_search($q, $i, $limit, $post_type=true){
require_once 'sphinxapi.php';
$ids = '33500';
$cl = new SphinxClient();
$cl->SetServer( "192.168.0.89" , 9667);
$cl->SetMatchMode( SPH_MATCH_EXTENDED );
$cl->SetSortMode ( SPH_SORT_RELEVANCE );
$cl->SetFieldWeights(array('post_title' => 300));
$cl->SetLimits( $i , $limit);
$q = $cl->EscapeString( $q);
//search url only
$q = $post_type ? "#post_type {$q}" : $q;
$result = $cl->Query( $q, 'sites sitesDelta' );
if ( $result === false )
error_log( '[SPHINX]Query failed: ' . $cl->GetLastError() );
elseif ( $cl->GetLastWarning() )
error_log( '[SPHINX]WARNING: ' . $cl->GetLastWarning() );
if ( !empty($result["matches"]) ){
foreach ( $result["matches"] as $doc => $docinfo )
$ids .= "$doc,";
$ids = substr( $ids, 0, -1 );
}else
return false;
return array( 'ids' => $ids, 'total' => $result['total'], 'docs' => count($result["matches"]) );
}
/*
* Connect to MySQL
*/
function db(){
if( !empty($GLOBALS['db']) ) return true;
if( !$GLOBALS['db'] = mysql_connect('localhost', 'root', '' ) ) {
die("[MYSQL]".mysql_error() . mysql_errno() );
}
elseif(!mysql_select_db('sphinxiirmulti')) {
die("[MYSQL]".mysql_error() . mysql_errno() );
}
}
?>

include sql result to php mail

I would like to ask if what is missing in my script for sending mail, my query is fine and it shows results and I'd like to ask for help on how to include those query result into the message that I will send out. I'd really appreciate it if you could give me an advice where to start. thanks.
<?php
$cfg = array(
'display' => 'gw#mail.com',
'address' => 'support#mail.com',
'subject' => 'TEST '
. date("m/d/t h:i:s A", strtotime('TODAY')) . ' hits',
'queries' => array(
"SELECT inbox.src AS 'From Mobile Number', outbox.dst AS 'To Mobile Number', outbox.stamp AS 'Timestamp', inbox.data AS 'Message', outbox.status AS 'Status' FROM mega.outbox LEFT JOIN mega.inbox ON outbox.pid=inbox.pid WHERE outbox.sid=156 && inbox.sid=156 && stamp > NOW() - INTERVAL 3 HOUR",
),
);
include "/var/xrelay/mysql.php";
$sql = new database();
$msg = '';
foreach( $cfg['queries'] as $i ) {
$tmp = $sql->read($i, true);
if (!empty($tmp)) {
foreach($tmp[0] as $k => $v) $msg .= "$k: $v\r\n";
}
}
foreach( preg_split( '/[\s,]+/', $cfg['address'], -1, PREG_SPLIT_NO_EMPTY) as $i ) {
$sql->write("INSERT INTO mega.emails (sender,recipient,subject,message,stamp) VALUES "
. "('{$cfg['display']}','$i','{$cfg['subject']}','".$sql->escape($msg)."', NOW());");
}
?>
Is there any way to improve this more? this mailer supposed to send mail to a recipient every 3hours if there are any activity from the db. it will retrieve data last 3 hours ago and put the result as message.
include "/var/xrelay/mysql.php";
$sql = new database('sql://gateway:xrelay#00.000.000.000/test');
$cfg = array(
'display' => 'gw#mail.com',
'address' => 'g#mail.com',
'subject' => 'MAIL HITS ' . date("m/d/y h:i:s A", strtotime("NOW")) . ' hits',
);
//define('DEBUG',true);
$result = mysql_query("SELECT outbox.dst, DATE_FORMAT(outbox.stamp,'%b-%d-%Y %h:%i %p')AS 'Stamp', outbox.status FROM mega.outbox LEFT JOIN mega.inbox ON outbox.pid=inbox.pid WHERE outbox.sid=156 && inbox.sid=156 && outbox.stamp > NOW() - INTERVAL 3 HOUR");
$msg='| Mobile# | Timestamp | Status |\r\n';
while($row = mysql_fetch_assoc($result))
{
$msg .= "| ". $row['dst'] ." | ". $row['Stamp'] ." | ". $row['status'] ." |\r\n";
}
$num_rows = mysql_num_rows($result);
echo $msg;
if($num_rows != 0){
foreach( preg_split( '/[\s,]+/', $cfg['address'], -1, PREG_SPLIT_NO_EMPTY) as $i ) {
$sql->write("INSERT INTO mega.emails (sender,recipient,subject,message,stamp) VALUES " . "('{$cfg['display']}','$i','{$cfg['subject']}','". $msg ."', NOW());");
}
}
?>
Once you have the results you should create a string that you would append to the body of the e-mail. You can use sprintf for this purpose.
If you are looking for a way to send the actual e-mail, the mail function is explained here.

Categories