I have a column in my database employee number and data which is ACZ2020000. When I add an employee, the generated employee number is ACZ2020002. How can I generate the ACZ2020001? Help me, please. Thanks so much, guys.
This what I did:
public function generate_employee_id() {
$query = $this->db->query("SELECT COUNT(*) AS num_rows FROM tbl_accounts");
$row = $query->fetch_object();
$number = $row->num_rows;
++$number;
$len = strlen($number);
for($i = $len; $i < 3; ++$i) {
$number = '0' . $number;
}
$employee_number = 'ACZ'. date("Y") . $number;
echo json_encode(['employee_number' => $employee_number]);
}
You want the highest number, something that doesn't have anything to do with the number of rows. If I understood the rules, you can do this to get the numbers already used:
SELECT employee_id, CAST(SUBSTR(employee_id, 5) AS signed) -- MySQL flavour
FROM tbl_accounts
WHERE employee_id LIKE 'ACZ20%'
... and good old MAX() to grab the latest:
SELECT MAX(CAST(SUBSTR(employee_id, 5) AS SIGNED)) + 1 AS next
FROM tbl_accounts
WHERE employee_id LIKE 'ACZ20%'
Said that, beware of potential issues caused by concurrent accesses!
Perhaps the best answer here would be to recommend not trying to manage your employee number sequence from your PHP application. Instead, let your database do that heavy lifting by way of an auto increment column or something similar. Note that if all employee numbers be prefaced by ACZ, then you really only need a way to generate a sequence, and this is something that databases are reasonably good at doing.
Related
I am looking way to sort the serial number of the table in descending order. I am using a here simple while loop, with a counter variable inside it.
Code sample:
$i= 0;
while(condition)
{
$i++;
echo "<td>".$i."</td>";
}
Output:
I am not using an autoincrement column here. I just want it with a simple counter, but in descending order.
example:
#
10
9
8
7
6
5
4
3
2
1
Any help is highly appreciated.
If you already have loop outputting the 1-10 version, you could simple change the output to show 11 minus the current count...
echo "<td>".(11-$i)."</td>";
Or to change the whole code, you could start at 11 and decrement the counter each time and output it that way
$i= 11;
while($i>0)
{
$i--;
echo "<td>".$i."</td>";
}
count first and after do a loop in reverse order
$i= 0;
while(condition)
{
$i++;
}
for ( cnt= $i, $i>= 0, $i--){
echo "<td>".$cnt."</td>";
}
If you are fetching from MYSQL Database and you're using PDO to connect to Database
//COUNT THE TOTAL NUMBER OF ROWS RETURNED
$sql = "SELECT COUNT(*) FROM all_tnxs ORDER BY id DESC";
$stmt = $con->query($sql);
$stmt_num_rows = $stmt->fetch();
$tot_rows = array_shift($stmt_num_rows);
$sn = $tot_rows
while(){
$sn--;
echo '<td>' . $sn . '</td>';
}
So whatever the total number of rows you have - fetching from the database it'll countdown to '0'using the while loop.
I have been looking for this for long but later figured it out myself so I decided to drop it here for anyone it might be helpful to...
How to burst the following rows into 3 groups where the sum of "dollars" is 10. All rows must be used and none more than once.
row|dollars
1|1
2|1
3|1
4|1
5|1
6|1
7|3
8|4
9|7
10|10
One (of many possible) desired outcomes would be...
Row Group 1 = 10
Row Group 2 = 7,9
Row Group 3 = 1,2,3,4,5,6,8
Extra Credit:
When it's not mathematically possible to get a sum of exactly $10 in each group, is there a formula for getting us closest to that?
I though maybe " HAVING sum(dollar) = 10 " or, for a close solution, just sorting and distributing one row to one group, but that didn't get me close.
Group Row By Sum of Specific Column equal to Specific Value sort of touches on this, but, assuming their could be millions of rows, there would be performance issues.
I'm stumped.
If it helps, I'm using php and mysql. A sql-only solution would be ideal, but some combination would be great too. Thanks for any suggestions.
Edit: If I wasn't clear, I want to return the rows that make this possible, not just "group by" them.
I don't think you could do it with just sql, but it could certainly help out. I'd start by having a query like select * from data where dollars <= 10 order by dollars desc and then make an algorithm in php that went through the results and added up dollars until it found three sets that add up to 10.
It would start out adding from larger to smaller until it found a correct sum, then store it, remove those items from the list and start again, three times. I'm on my phone, but will update the answer with a working example when I get to my computer.
EDIT: got to my computer. This is very messy code, but it should lead you in the right direction.
$dataset = [10,7,4,3,1,1,1,1,1,1];
$results = [];
function add_to_ten(&$data) {
$sum = 0;
$results = [];
foreach ($data as $index => &$datum) {
if ($datum == 0) {
continue;
}
if ($sum + $datum <= 10) {
$sum += $datum;
$results[] = $index;
$datum = 0;
}
if ($sum == 10) {
return $results;
}
}
}
print_r(add_to_ten($dataset));
print_r(add_to_ten($dataset));
print_r(add_to_ten($dataset));
I am trying the use refine tools for a search on my website. The bit i'm stuck with is search by start letter. For example i could use a wildcard '%X%' but his would return anything that contained the letter 'x'.
I read on few sites that SUBSTRING can be used in mysql queries
http://dev.mysql.com/
http://www.kirupa.com/
https://stackoverflow.com/questions/6302027
This is what I have so far but returns nothing. There is data in the database that should return with the query.
public function refineUsersFollowers($user_id,$q){
if($this->databaseConnection()){
// get the users followers
$state = array(1,2);
$stmt = $this->db_connection->prepare("SELECT * FROM friends WHERE id_2 = :1 AND Friend_Request_State = :2 OR id_2 = :3 AND Friend_Request_State = :4");
$stmt->bindParam(':1', $user_id);
$stmt->bindParam(':2', $state[0]);
$stmt->bindParam(':3', $user_id);
$stmt->bindParam(':4', $state[1]);
$stmt->execute();
// format the SQL OR statements
$sql = '';
$ids = [];
while($rows = $stmt->fetch(\PDO::FETCH_ASSOC)){
array_push($ids,$rows['id_1']);
}
for($x = 0; $x < count($ids); $x++){
if(count($ids) == 1){
//if there is one result
$sql.= ' user_id = :'.$x." AND SUBSTRING('first_name',0,1) = :".$x.$x;
}else if($x == (count($ids) - 1)){
// last entry
$sql.= ' user_id = :'.$x." AND SUBSTRING('first_name',0,1) = :".$x.$x;
}else{
//continue loop
$sql.= ' user_id = :'.$x." AND SUBSTRING('first_name',0,1) = :".$x.$x." OR";
}
}
$stmt = $this->db_connection->prepare("SELECT * FROM account WHERE ".$sql);
for($x = 0; $x < count($ids); $x++){
$stmt->bindParam(':'.$x,$ids[$x]);
$insert = $x.$x.'';
$stmt->bindParam(':'.$insert,$q);
}
$stmt->execute();
$results = $stmt->fetch(\PDO::FETCH_ASSOC);
print_r($results);
// check for followers that start with letter
}
}
The first part of the function is fine, this gets an array of id's which is then placed together as an SQL string. Is the SQL not returning results because SUBSTRING is not supported in this way?
If so is there a way of producing a query like this or would it be easier to pull every result from the database then check them in a different function?
You have two issues with this expression:
SUBSTRING('first_name', 0, 1) = :".$x.$x;
First, substr() in SQL (in general) starts counting with 1 and not 0. So, the first argument should be 1.
Second, you have the first argument in single quotes. So, at best, this would return the letter 'f'. Here is a simple rule: Only use single quotes for string and date constants. Never use single quotes to refer to column names.
There are several way to write what you want. Here are three:
SUBSTRING(first_name, 1, 1) = $x
LEFT(first_name, 1) = $x
first_name like '$x%'
You query can be greatly simplified with the LIKE operator. This:
"AND SUBSTRING('first_name',0,1) = :".$x.$x;
can become this:
"AND first_name LIKE '".$x.$x."%'";
I'm not sure what the $x.$x is for, so I just left it in for illustrative purposes.
I am working on a scratch card game where by a user purchases a scratch card from me/my store and can then redeem said card by scratching off numbers and matching 3 pictures to win a prize
Like physical scratch cards I want the prizes to be pre configured so that I know when a prize will be won, but obviously the users dont, this is so I can limit the prizes, so it is not true random, but will be random in terms of who wins the prize..
I know how I will setup the prizes but I need to check each data value in an array to ensure that there is not 3 matching numbers, unless they have actually won..
So far I have this (I will neaten it up and shorten the code down soon)
$numbers = array(
0 => rand(0,9),
1 => rand(0,9),
2 => rand(0,9),
3 => rand(0,9),
4 => rand(0,9),
5 => rand(0,9),
6 => rand(0,9),
7 => rand(0,9),
8 => rand(0,9)
);
Which just randomly generates 9 numbers and
echo "<table>";
$i=0;
for($x=0;$x<3;$x++){
echo "<tr>";
for($y=0;$y<3;$y++){
echo "<td>" . $numbers[$i] . "</td>";
$i++;
}
echo "</tr>";
}
Sorts them into a 3x3 table
I know there is the command in_array() which will sort through the array looking for certain values but I dont want to run an endless loop checking each value to see if I get a match, because it's labor intensive and would be messy as well.
I'm looking for a suggestion anyone might have so I can sort through the array and see if any 3 numbers exist, if they do, and they're not suppost to (ie the user hasn't actually won a prize) then one should be changed to a new number.
So thank you in advance for your help guys I look forward to your suggestions
Luke
**** EDIT **
+More info
To pick the winners I will use a database query such as this
$stock = $conn -> query("SELECT DISTINCT * FROM codes WHERE Available = 1 AND 0 = FLOOR(RAND()*Chance) ORDER BY RAND()");
Each code will have a set chance to win and if it matches up it will be shown, depending on the code won a certain prize will show
$stock = $conn -> query("SELECT DISTINCT * FROM codes WHERE Available = 1 AND Win = 1);
'Win' will be a table in the database which each time someone plays the game it goes down by 1
So each code will have the table Win which when it hits 1 it will pop out the in the next game
These are two ways I can think of doing it which I think will work, both ways roughly allow me to control when and if someone wins but the second solution is obviously a more accurate way of doing it
how about not changing a number if a triple one occurs, but preventing a triple one occurs.
function createScratchRange()
{
$result = array();
$options = array_merge(range(0,9), range(0,9));
for ($i = 0; $i < 9; $i++)
{
$key = array_rand($options, 1);
$result[] = $options[$key];
unset($options[$key]);
}
return $result;
}
and you might want to be able to create winners:
function createWinner()
{
$winningNumber = rand(0,9);
$result = array();
$possibleNumbers = range(0,9);
unset($possibleNumbers[$winningNumber]);
$options = array_merge($possibleNumbers,$possibleNumbers);
for ($i = 0; $i < 9; $i++)
{
$key = array_rand($options, 1);
$result[] = $options[$key];
unset($options[$key]);
}
// looks random now.. but no winning numbers... Lets just stick them in there.
$keys = array_rand($result, 3);
foreach($keys as $key)
{
$result[$key] = $winningNumber;
}
return $result;
}
and for testing:
var_dump(createScratchRange()); // this will never give 3 identical numbers in the array.
var_dump(createWinner()); // this will ALWAYS give 3 identical numbers, but never 2 sets of 3 identical numbers
I want to generate the lotto number like generating here
http://www.nationallottery.co.za/lotto_home/NumberGenerator.asp
may i know what will be the logic or way to generate the lotto number using PHP,mysql and Ajax.
I will be thankful of you.
Sample Example:
$generated = array();
while (count($generated) < 6)
{
$no = mt_rand(1, 49);
if(!array_search($no, $generated))
{
$generated[] = $no;
}
}
echo implode(" : ", $generated);
You just need to generate random numbers.
Create multiple random numbers and style them however you want them. That site appears to have replaced text numbers with images which are probably programatically coded. If you want multiple rows like they offer, just make a form like they have and return the correct number of rows. Shouldn't be too hard
The php function you are looking for is mt_rand()
Use it to generate an integer between two given values, something like this:
<?php
for($i = 1; $i <= 6; $i++){
echo mt_rand(1,45).' ';
}
?>