Can not add automatic numbers behind with php - php

I have the code from the database, the data should appear automatically in sequence. the code is composed of text and number like this CO-00001 but when I generate the code it just adds one digit in the back but not add the value of example CO-00001 to CO-000001 how to solve it?
ex :
$id = 0902340
$query = "SELECT substr(code_id,3,5) as cd FROM tb_inv WHERE substr(code_id,3,5) = '".$id."' ORDER BY code_id DESC LIMIT 1";
$get_id = $this->db->query($query);
$show_id = $get_id->num_rows();
$new_code = $get_id->row();
if($show_id > 0){
$new = $new_code->cd + 1;
$fix_code = $new;
}else{
$fix_code = 'CO-00001';
}

you can't do algebra on alphabets, therefore you need to split the alphabets and the numerics like so:
$id = 0902340
$query = "SELECT substr(code_id,3,5) as cd FROM tb_inv WHERE substr(code_id,3,5) = '".$id."' ORDER BY code_id DESC LIMIT 1";
$get_id = $this->db->query($query);
$show_id = $get_id->num_rows();
$new_code = $get_id->row();
if($show_id > 0){
$prefix = substr($new_code->cd, 0, 3); // get the prefix 3 chars at front
$number = substr($new_code->cd, 3); // get the remaining chars
$new = $number + 1; // add it with 1, php automatically convert strings that can be converted to numbers
$fix_code = $prefix . substr("00000" . $number, -5); // re-assemble the code
}else{
$fix_code = 'CO-00001';
}

you can split the id into two parts, the string one, and the digit one. then increment the digit part then re concat the two parts again
list($strPrefix, $digitPart) = split('-', $oldId);
$digitPart++;
$newCode = $strPrefix . '-' . $digitPart;

Related

Can I get value from mysql table and set it as variable?

I have attribute_description like in the image :
on table I have for cap_tabel values: d, lt, lu, amb, coada
I want to get them and make it variable and set the value equal to the attribute_id.
eg:
$d = 1;
$lt = 2;
$coada = 9;
I think i can create a function.php file where this variables are created and use them where is needed.
Is this possible or I have to create a script where I name the variable myself and set it the right value like:
$amb_ext = mysqli_fetch_array(mysqli_query($connect,"SELECT attribute_id FROM attribute_description WHERE cap_tabel='amb'"));
$amb = $amb_ext['attribute_id'];
What do you think is the best solution?
In the end I want to create a product table where in th will be value from cap_tabel and in td to get the right value with the correct th cell
You could use variable variables:
$res = mysqli_query($connect,"SELECT attribute_id, cap_tabel FROM attribute_description");
while ($row = $res->fetch_assoc()) {
$var = $row['cap_tabel'];
$$var = $row['attribute_id'];
}
// you now would have variables $d, $lt, etc
$result = mysqli_query($connect,"SELECT attribute_id, cap_tabel FROM attribute_description");
while ($aValue = mysqli_fetch_array($result)) {
${$aValue['cap_tabel']} = $aValue['attribute_id'];
}
echo ' $d = ' . $d . ', $lt = ' . $lt . ', $coada = ' . $coada;
To get result like this :
$d = 1, $lt = 2, $coada = 9

add value +1 in phrase number

I want to add value in phrase in database sql in database i save phrasr like this
DO-2500-01
DO-2500-02
now my question how can add +1 in last value like this DO-2500-03 / DO-2500-04
this my code
$getse = $DB_con->prepare("SELECT serial FROM `customer` WHERE user_add=:id ORDER BY serial DESC LIMIT 1");
$getse->execute(array(":id"=>$user_id));
$getse = $getse->fetch(PDO::FETCH_OBJ);
$addone = $getse->serial + 1;
echo $addone;
this is my code i get last serial and i want to add +1 for example last serial in database is DO-2500-04 I want to get this value and add +1 To become like this DO-2500-05
Split string, increase the last part and combine it back
$addone = explode('-', "DO-2500-04");
$addone[count($addone)-1] += 1;
// Append 0 if the last part less then 10
$addone[count($addone)-1] = str_pad($addone[count($addone)-1], 2, 0, STR_PAD_LEFT);
echo $addone = implode('-', $addone);
You can get this based on your requirement.
If DO-2500-99 should be DO-2501-00 then below code can work.
$serialArr= explode('-', $getse->serial);
$serialNo = (int)$serialArr [1].$serialArr [2];
$newSerialNo = $serialNo + 1;
$newSerialNo = substr($newSerialNo, 0, -2)."-".substr($newSerialNo , -2);
$newSerial = $serialArr[0].'-'.$newSerialNo;
If DO-2500-99 should be DO-2500-100 then below code can work.
$getse = 'DO-2500-99';
$serialArr= explode('-', $getse->serial);
$serialNo = (int)$serialArr [2];
$serialArr[2] = $serialNo + 1;
$newSerial = implode('-',$serialArr);
DO-2500-04 it's a String value and you cannot use arithmetic operators on it. If you just want last counter to get incremented, what you need to do is get the last value by splitting the string by -.
Then get the last value and increment it and then again join the array by -.
To split and join the array we can use explode() and implode().
This is how you can get the last value from string using explode()
$values=explode("-","DO-2500-04"); // $values is now array.
$lastvalue=(int)$values[2];
$lastvalue++;
if($lastvalue<9) {
$lastvalue = "0" . $lastvalue;
}
$values[2]=$lastvalue;
$incremented_string=implode("-",$values);
First parameter in explode denotes the chracter by you want to split the string same as first parameter in implode denotes the glue by you want to join the array.
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
Just for fun, you could do a lot of this in the SQL like:
$getse = $DB_con->prepare("SELECT serial,
LEFT(serial,8) AS serialBase,
SUBSTRING(serial,8) AS serialIdx
FROM `customer` WHERE user_add=:id
ORDER BY serial DESC LIMIT 1");
$getse->execute(array(":id"=>$user_id));
$getse = $getse->fetch(PDO::FETCH_OBJ);
$addone = $getse->serialBase + str_pad(($getse->serialIdx + 1),2,'0',STR_PAD_LEFT);
echo $addone;
Updated the SQL.

How to increment a default value in mysql

I have a field (demo_field)(varchar) in mysql table. I want to increment this field value with a pre defined prefix.
For example my field first value is demo001. Now when ever new values inserted I want to increment the numeric numbers like demo002, demo003.
How can I do this with PHP.
try this -
//fetch data from table
$sql = $mysqli->query('select count(demo_field) as total,demo_field from tablename limit 1');
$res = $sql->fetch_assoc();
//generate string from existing data
$str = substr($res['demo_field'], 0, 4);
$dig = str_replace($str, '', $res['demo_field']);
$dig = $dig+$res['total'];
//add padding if needed
$dig = str_pad($dig, 3, '0', STR_PAD_LEFT);
//concatenate string & digits
$newStr = $str.$dig;
var_dump($newStr);
Another way without count
$sql = $mysqli->query('select max(demo_field) as demo_field from demo');
$res = $sql->fetch_assoc();
$str = substr($res['demo_field'], 0, 4);
$dig = str_replace($str, '', $res['demo_field']);
$dig += 1;
$dig = str_pad($dig, 3, '0', STR_PAD_LEFT);
$newStr = $str.$dig;
var_dump($newStr);
hope this might solve the problem with count.
another solution with max count for alphanumeric string and without padding -
$sql = $mysqli->query('select max(cast(substring(demo_field, 5) as unsigned)) as digit, demo_field from demo');
$res = $sql->fetch_assoc();
$str = substr($res['demo_field'], 0, 4);
$dig = $res['digit'] + 1;
$newStr = $str.$dig;
var_dump($newStr);
//use PHP not mysql
$pre = 'demo';
$num = 0;
define('MAX', 100);
for($num = 0; $num < MAX; $num++)
{
$pre_str = $pre . sprintf("%03d", $num);
//insert here
}
you have to use an INT field
and translate it to whatever format you want at "select" time.
In MySQL we cannot use AutoIncrement for Varchar.

make a unique, random number to use as an order ID

I'm working right now to get a unique order number for the item being purchased.
The problem is such that I have payment gateway at quickpay and it comes up and says this: "Error in field: ordernumber"
I have tried to make it like this:
$idag = date("dmY");
$a = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz#!*_-?>/+,ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 4);
$total = $idag . $a;
$sql = "SELECT pakker.pris FROM pakker WHERE pakker.id = 3";
if ($stmt = $this->mysqli->prepare($sql)) {
$stmt->execute();
$stmt->bind_result($pris);
while ($stmt->fetch()) {
$protocol = '7';
$msgtype = 'authorize';
$merchant = '89898978';
$language = 'da';
$ordernumber = $total;// here must order number came up.
I have also tried to do it like this.
$idag = date("dmY");
$rand = strtoupper(substr(uniqid(sha1(time())), 0,8));
$a = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz#!*_-?>/+,ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 4);
$total = $idag . $a . $rand;
From the [API documentation for Quickpay]:
ordernumber
/^[a-zA-Z0-9]{4,20}$/
A value by merchant's own choice. Must be unique for each transaction. Usually an incrementing sequence. The value may be reflected in the your bank account list.
You need to alter your random order ID generator to exclude any non-alphanumeric characters.
i.e.
$idag = date("dmY");
$a = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 4);
$total = $idag . $a;
if I were you, I'd use the unix timestamp and then add a few extra characters to the end.

how to limit my mysql select characters

I am grabbing info from three rows in my table, and echoing one of them in a anchor tag.
How can I limit the amount of characters on the $title variable that are shown in the anchor tag.
Code:
$results = mysql_query("SELECT * FROM news ");
while($row = mysql_fetch_array($results)) {
$id = $row['id'];
$title = $row['title'];
$date = $row['date'];
echo "$title | ";
}
$thisID = $_GET['id'];
if(!isset($thisID)) {
$thisID = 7;
}
You can use substr:
echo "" . substr($title, 0, LENGTH) . " | ";
Replace LENGTH with the length in characters to which you want to trim $title.
You can use LEFT in the query to return the leftmost set of characters from a column.
It's in the format of LEFT(column, max_chars)
define('MAXCHARS', '50');
$results = mysql_query("SELECT id, LEFT(title, ".MAXCHARS.") as truncated_title,
date FROM news");
Now when you go to retrieve the column, aliased by truncated_title in this example, it will only contain at most however many characters as set in your MAXCHARS constant.
You could replace the first part of the string, or the last part, but if you do it would be better to provide an indication that something has been left out, by appending or prepending an ellipsis ...

Categories