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.
Related
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;
Let's say i have a number 1234567890 andi want to do some sort of loop that creates something usable in an MySQL query.
For example:
Number is 1234567890.
The usable part in the query should look like:
SELECT * FROM table WHERE column IN (1234567890, 123456789, 12345678, 1234567, 123456, 12345, 1234, 123, 12, 1)
breaking my head on this one so i hope someone can help me out.
Thank you very much in advance...
Is this what you want?
where '1234567890' like concat(column, '%') and length(column) > 0
$number = "1234567890"; // Has to be string
$array = array();
while( strlen($number) > 1 )
{
$array[] = $number;
$number = substr($number, 0, strlen($number)-1);
}
$strForMySQL = implode(",", $array); // would return "1234567890,123456789,12345678,........1"
$query = "SELECT * FROM table WHERE column IN (".$strForMySQL.")";
You could use substr to keep stripping the last character of the number with a loop. If you start with an integer, you will need to type cast this into a string for it to work.
$x=1234567;
$x=(string)$x;
for($i=0; $i<strlen($x); $i++){
//Write SQL here or store them in an array, print...etc.
echo substr($x, 0,strlen($x)-$i);
}
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 trying to add leading zeros to all skus in my table. I need every sku to have a 3 digit number in front of it. For 1-9 skus would be 001$row['sku'], 002$row['sku'], 009$row['sku'], 010$row['sku'], 011$row['sku'],...etc I am using $n=sizeof($row). But every time I echo this out I get 22 skus (which there are about 50) and only returns the first letter of the sku. I don't understand how to fix this, I am trying to build an array from my query to determine how many skus there are in order to add leading zeros. Any help is much appreciated.
$result = mysql_query("SELECT * FROM temp_table WHERE po='ABCD'");
$row = mysql_fetch_array($result);
for ($i=0, $n=sizeof($row); $i<$n; $i++) {
if ($i < 9) {
$Zeros="00";
}
elseif ($i < 99) {
$Zeros="0";
}
else{
$Zeros="";
}
$num=$i+1;
echo $Zeros.$num. "=" . $row[$i]['sku'] . "`<br />`";
You aren't looping through the resulting data set quite right, or I don't fully understand the situation.
Assuming you want to build a three-digit SKU based on each row's SKU, here's a better way:
// query the database
$result = mysql_query("SELECT * FROM temp_table WHERE po='ABCD'");
$count = 0;
// Loop through every row in the data result set
while ( $row = mysql_fetch_assoc( $result ) ){
$count++; // Increment SKU #
// Build integer SKU based on count of item in order and pad with zeros
$this_sku = str_pad( $count, 3, '0', STR_PAD_LEFT);
// Build onto integer SKU based on row data and pad with zeros
$this_sku .= str_pad( $row['sku'], 3, '0', STR_PAD_LEFT);
echo "This product SKU is $this_sku<br/>";
}
I don't fully understand the context, but it sounds as though you want to be using the str_pad function.
e.g.
$num1 = str_pad(1, 3, '0', STR_PAD_LEFT); // = 001
$num2 = str_pad(10, 3, '0', STR_PAD_LEFT); // = 010
// etc...
You are looking for the str_pad function.
example:
$num = str_pad($input, 4, "0", STR_PAD_LEFT);
The most elegant way is use sprintf() http://php.net/manual/en/function.sprintf.php
sprintf(%'0'3d=%d`<br />`, $num, $row[$i]['sku']);
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 ...