At the moment this is my function to create a random unique invoice number which is stored in a form's hidden field
function generate_invoice_number() {
global $wpdb;
$lastVisitor = $wpdb->get_results("SELECT visitorID FROM event_visitors_2014 ORDER BY visitorsID DESC LIMIT 1", ARRAY_A);
$nr_last = $lastVisitor[0]['visitorID'];
$nr = 501 + $nr_last;
$value = sprintf( '%04d', $nr );
$number = 'LEDEXPO'.date('Y').'-'.uniqid().'-'.$value;
return $number;
}
I have a problem when multiple people are using the form at the same time, say 3 people are using the form they all have the same number generate.
So i added uniqid(), so $value could be duplicated but $number should be unique? Is this correct or is there a better way?
How can i make test function to test this function on uniqueness?
regards
Try This:
function generate_invoice_number()
{
global $wpdb;
$lastVisitor = $wpdb->get_results("SELECT visitorID FROM event_visitors_2014 ORDER BY visitorsID DESC LIMIT 1", ARRAY_A);
$nr_last = $lastVisitor[0]['visitorID'] + 1;
$number = date('Ymd') . $nr_last;
return $number;
}
Related
everyone.
In the codeigniter there is update_batch function by using it we are able to bulk update multiple rows.
$this->db->update_batch('table_name', $update_data_array, 'where_condition_field_name');
I want similar functionality in core PHP in one function or in one file. Is there any workaround?
Is there any way to extract update_batch function from Codeigniter in one file/function?
I tried to extract this function but it is very lengthy process and there will be many files / functions should be extracted.
Please help me in this regard
Thanks in advance
You can also insert multiple rows into a database table with a single insert query in core php.
(1)One Way
<?php
$mysqli = new mysqli("localhost", "root", "", "newdb");
if ($mysqli == = false) {
die("ERROR: Could not connect. ".$mysqli->connect_error);
}
$sql = "INSERT INTO mytable (first_name, last_name, age)
VALUES('raj', 'sharma', '15'),
('kapil', 'verma', '42'),
('monty', 'singh', '29'),
('arjun', 'patel', '32') ";
if ($mysqli->query($sql) == = true)
{
echo "Records inserted successfully.";
}
else
{
echo "ERROR: Could not able to execute $sql. "
.$mysqli->error;
}
$mysqli->close();
? >
(2)Second Way
Let's assume $column1 and $column2 are arrays with same size posted by html form.
You can create your sql query like this:-
<?php
$query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
$query_parts = array();
for($x=0; $x<count($column1); $x++){
$query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
}
echo $query .= implode(',', $query_parts);
?>
You can easily construct similar type of query using PHP.
Lets use array containing key value pair and implode statement to generate query.
Here’s the snippet.
<?php
$coupons = array(
1 => 'val1',
2 => 'va2',
3 => 'val3',
);
$data = array();
foreach ($coupons AS $key => $value) {
$data[] = "($key, '$value')";
}
$query = "INSERT INTO `tbl_update` (id, val) VALUES " . implode(', ', $data) . " ON DUPLICATE KEY UPDATE val = VALUES(val)";
$this->db->query($query);
?>
Alternatively, you can use CASE construct in UPDATE statement. Then the query would be something
like:
UPDATE tbl_coupons
SET code = (CASE id WHEN 1 THEN 'ABCDE'
WHEN 2 THEN 'GHIJK'
WHEN 3 THEN 'EFGHI'
END)
WHERE id IN(1, 2 ,3);
I want to get total amount from foreach lop data in the controller, for example, code bellow.
$set = settings::findOrFail(1);
$api = new \Binance\API("$set->api_key","$set->scrt_key");
$api->useServerTime();
$forusdvaluetotal = coins::whereuser_id(Auth::user()->id)->get();
foreach($forusdvaluetotal as $coins){
$getsymbol = $coins->symbol.'USDT';
$getprice = $api->price("$getsymbol");
$valueinusd = $coins->balance*$getprice;
$total = $valueinusd;
}
$gettotal = $total->sum();
like "coins A" price is $50 per coin and balance 2, "coins B" price is $50 per coin and balance 5, "coins C" price is $50 per coin and balance 1. So I want to get total amount in USD by balance like ('coins A' $502 = $100 + 'coins B' $505 = $250 + 'coins A' $50*1 = $50) = $400
Please help me how to solve that in laravel controller.
Try this:
$total = 0;
foreach($forusdvaluetotal as $coins){
$getprice = $coins['market_price'];
$valueinusd = $coins['balance']*$getprice;
$total += $valueinusd;
}
return $total;
One elegant option would be to make use of Laravel's support collection method reduce().
The reduce method reduces the collection to a single value, passing
the result of each iteration into the subsequent iteration:
The value for $carry on the first iteration is null; however, you
may specify its initial value by passing a second argument to
reduce:
$collection = coins::whereuser_id(Auth::user()->id)->get();
$total = $collection->reduce(function ($carry, $item) {
return $carry + (floatval($item->balance) * floatval($item->market_price));
}, 0);
Addendum
Alternatively, you may make use of Laravel's support collection method sum().
The sum method returns the sum of all items in the collection:
In addition, you may pass your own closure to determine which values
of the collection to sum:
$collection = coins::whereuser_id(Auth::user()->id)->get();
$total = $collection->sum(function ($item) {
return (floatval($item->balance) * floatval($item->market_price));
});
Edit:
In response to your new question changes, you could solve it this way.
$set = settings::findOrFail(1);
$api = new \Binance\API("$set->api_key","$set->scrt_key");
$api->useServerTime();
$query = coins::whereuser_id(Auth::user()->id);
// Get symbols.
$symbols = (clone $query)->distinct('symbol')->pluck('symbol')->flip()->toArray();
// Fetch prices.
array_walk($symbols, function (&$value, $key) use ($api) {
$value = $api->price("{$key}USDT");
});
// Get total sum.
$total = $query->get()->reduce(function ($carry, $item) use ($symbols) {
return $carry + (floatval($item->balance) * floatval($symbols[$item->symbol]));
}, 0);
While Searching I want to show the paid customers firstly, and then rest of customers list
but the problem is I want to show by random
for Example. paid customers should not mix with others.
Can anyone tell what will be query?
please help me!
I am using codeigniter
Example:
function randomval()
{
$this->db->order_by('id', 'RANDOM');
$this->db->limit(1);
$query = $this->db->get('tblname');
return $query->result_array();
}
Mysql query for your need if i understood well
SELECT `featured`,group_concat(`id` order by rand() ) as `id` FROM `dbc_posts` where `status` = 1 GROUP By `featured` ORDER BY `featured` DESC
now with php
$results = $this->db->query("SELECT `featured`,group_concat(`id` order by rand() ) as `id` FROM `dbc_posts` where `status` = 1 GROUP By `featured` ORDER BY `featured` DESC")->result_array();
$paid = $results[0];//featured = 1
// comma seprated ids of the paid people e.g :- 3,7,1,26,92 are available in
$paidusers = $results[0]["id"];
//seprate them by
$paidusers = explode(",",$paidusers);
foreach($paidusers as $paiduser)
{
$row = $this->db->get_where("dbc_posts", array("id"=> $paiduser))->row();
print_r($row );
echo "<br>";
}
// do same for unpaid
$unpaid = $results[1];//featured = 0
$unpaidusers = $results[1]["id"];
//seprate them by
$unpaidusers = explode(",",$unpaidusers);
foreach($unpaidusers as $unpaiduser)
{
$row = $this->db->get_where("dbc_posts", array("id"=> $unpaiduser))->row();
print_r($row );
echo "<br>";
}
Ask me if anything goes wrong
Set featured = 1 for paid and featured = 0 for unpaid customers in database. Then use the query
mysql_query("SELECT * FROM dbc_posts WHERE status = 1 ORDER BY featured DESC, RAND() LIMIT 1");
I am an amateur programmer that needs the help of a real one to resolve this beautiful problem, because I must admit that I am really stuck on this one!
In my database I have a « tslines » table that contains a value (sum_week) for a given week(startdate) and a given contract(contract_id)
The fields that are important are : sum_week, user_id , startdate and contract_id
I also have a « users » table, the important values are « first_name, last_name »
I have many workers that have worked on a contract, at different times (startdate, represents the first day of the week)
Example (table below): I can have 3 lines for worker A, and 2 lines for worker B
For some week(startdate), it can happend that no one worked on the contract
I want to show a table with those informations, for contract_id=3(ex) (this field is in tslines table) :
sum_week is a field, I don't want to recalculate with a SQL query
I don’t want to run a query for each weeks to check for each user if he worked on a contract because that would become a problem if I have ex : 30 weeks with 30 users that worked on the project..
I started by building an array of all possible « startdate »
//Selects min and max startdate of the tslines, use $dates->maxdate and ->mindate
$dates = $contract->tslines()->whereIsOfficial(true)->select(DB::raw('MAX(startdate) as maxdate, MIN(startdate) as mindate'))->first();
//Define first date declared in tslines
$loopdate = Carbon::parse($dates->mindate);
$maxdt = Carbon::parse($dates->maxdate);
//While loop to create array of date ranges from min to max
$date_count = 0;
$daterange = array();
while($loopdate->gt($maxdt) == false)
{
$daterange[] = $loopdate->format('Y-m-d');
$loopdate->addDays(7);
$date_count++;
}
I know I have to do some array manipulations but I really don’t know from where to start, even witht the queries..
I can get all the related tslines of contract by doing:
$contract->tslines()->get()
But I dont't know how to build an array that contains user information and all the startdate (even if he didn't work that week)
Can anybody give me some hints.. It would be greatly appreciated!!
Thanks in advance!
Raphaël
Let's start from what we know.
We know which users have worked on which contracts and on what date.
With your function above, we have the max date and the min date a user has started working on a contract.
Solution:
$tslines = $contract->tslines()->orderBy('user_id','ASC')->orderBy('startdate','ASC')->get();
//I didn't see any relationship calls to the user's object, so you'll have to add one of your own. I am assuming, your `tslines` has a relationship `user` here.
$userListResult = $contract->tslines()->with('user')->orderBy('user_id','ASC')->select(\Db::raw('distinct("user_id")')->get();
$dates = $contract->tslines()->whereIsOfficial(true)->select(DB::raw('MAX(startdate) as maxdate, MIN(startdate) as mindate'))->first();
$minDate = Carbon::parse($dates->mindate);
$maxDate = Carbon::parse($dates->maxdate);
//we flatten the array for future use.
$userList = array();
foreach($userListResult as $l)
{
$userList[$l->user_id] = $l->user->first_name.' '.$l->user->last_name;
}
//Assuming you are printing a table in blade
<table>
<?php
//Print the table headers
echo"<tr>
<td>User</td>";
$currDate = clone($minDate);
do
{
echo "<td>".$currDate->format('Y-m-d')."</td>";
$currDate->addDay();
}
while($currDate->diffInDays($maxDate) !== 0);
echo "</tr>";
//Print each user's row
foreach($userlist as $userid => $username)
{
echo "<tr>
<td>
$username
</td>";
$currDate = clone($minDate);
//loop through all the dates in range (min to max date)
do
{
$foundDate = false;
//We check if user has worked on that day
foreach($tslines as $row)
{
if($row->user_id === $userid && $row->startdate->format('Y-m-d') === $currDate->format('Y-m-d'))
{
//Print result if startdate & userid matches
echo "<td>{$row->sum_week}</td>";
$foundDate = true;
//Get out of the loops
break;
}
}
if(!$foundDate)
{
echo "<td>X (didn't work)</td>";
}
$currDate->addDay();
}
while($currDate->diffInDays($maxDate) !== 0);
echo "</tr>";
}
?>
</table>
I am creating an order cart.
On the page that displays the cart, it checks if a value stored in the session $order corresponds with an id of a row in a mysql table. If this match exists, then the corresponding row is returned.
Within this process, I am trying to retrieve the quantity value stored in the session $quantity that corresponds to the id of the row in the table.
Each value in $order and $quantityis assigned a name, which is the id of the item they were added from.
This is the code that adds the order to the cart:
if (isset($_POST['action']) and $_POST['action'] == 'Order')
{
// Add item to the end of the $_SESSION['order'] array
$_SESSION['order'][$_POST['id']] = $_POST['id'];
$_SESSION['quantity'][$_POST['id']] = $_POST['quantity'];
header('Location: .');
exit();
}
This is the code on the cart page:
foreach ($order as $item)
foreach ($quantity as $amount)
{
mysql_data_seek( $productsSql, 0); //<- this line, to reset the pointer for every EACH.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
if ($item == $itId)
{
$pageContent .= '
<tr>
<td>'.$itDesc.'</td>
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
<td>R'.number_format($itPrice1*$amount, 2).'</td>
</tr>
';
}
}
}
This row is producing a syntax error:
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
What is the problem here for starters?
Secondly, how would I need to do to accomplish the task that I am facing?
Any input on this would be greatly appreciated!
Could you try this?
<td>'.($item[$itId] == $amount[$itId] ? $amount : '').'</td>
This is a ternary operator, look at http://en.wikipedia.org/wiki/Ternary_operation
You can't simply add conditional statements like that while you're building a string.
You can do this, however
<td>' . ($item[$itId] == $amount[$itId]) ? $amount : null . '</td>
but you should use a more legible method.
Another issue you may get is if $amount is an array, you won't be able to print it as a string. If, however, $amount is an object with ArrayAccess interface, you can print it with the __toString() method; but that's another story.
The code for creating the cart page has several issues.
You walk over items and over quantities, which will probably give you duplicate outputs.
$item is a plain string, so I wonder what $item[$itId] is supposed to do?
You walk over your complete result set several times which actually is not necessary. I really hope that "$productSql" isn't a "select * from product", otherwhise this might get REAL slow in production mode.
I suggest creating a good SQL for getting the data and using this as a basis for filling the page:
// note this has SQL-injection issues, so you really need to make sure that $order contains no crap
$productsSql = mysql_query("select * from product where id in (".join($order, ',').")");
// you now have a result set with all products from your order.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
// session contains the quantity array mapping ID -> Quantity, so grab it from there
$itQuantity = $quantity[$itId];
// finally calculate the price
$itPrice = number_format($itPrice1*$itQuantity, 2);
// now you have all data for your template and can just insert it.
// if you use double quotes you can put the $xyz into the string directly
$pageContent .= "
<tr>
<td>$itDesc</td>
<td>$itQuanty</td>
<td>R $itPrice</td>
</tr>
";
}