how to limit my mysql select characters - php

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 ...

Related

Add Numbers Together From Mysql Database in PHP

I need to add some numbers together that are being pulled from a MySQL table to get a total value.
Currently the issue I have is the numbers being added to the end of a string instead.
e.g:
1,2,3,4 becomes 1234 instead of 10
Here is what I am using to get the numbers from the database:
$count = mysqli_query($connect, "SELECT QUANTITY FROM Table");
while($row = mysqli_fetch_assoc($count)) {
$total .= $row['Quantity'];
//I Have also tried
$total .= (int)$row['Quantity'];
}
echo $total;
The Quantity Column is set to be an INT in the table so I would have expected it to add together automatically. What am I doing wrong?
You should probably look at the difference between .= and +=
By adding a . in front of = you concatenate - You add the value ad the end of the variable.
If you would use a + in front of your = you would actually get the result you want.
$count = mysqli_query($connect, "SELECT QUANTITY FROM Table");
$total = 0;
while($row = mysqli_fetch_assoc($count)) {
$total += $row['Quantity'];
}
echo $total;
http://php.net/manual/en/language.operators.string.php

Can not add automatic numbers behind with 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;

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.

on click link display string which first character is between 0-9

Am trying to display a string from my database where the first character is between 0 to 9 i tried it but still did not work below is my code help me with it thanks.
if(isset($_REQUEST['num'])){ $num = explode('-',$_REQUEST['num']);
$query1 = "SELECT usercode FROM user WHERE code like '".$num."%'" ORDER BY id DESC ";
$result1 = mysql_query ($query1) or die('query error');
while( $line1 = mysql_fetch_assoc($result1)){
echo $line1[usercode];
}
#
Your code is currently searching your database for Array since you are explode()'ing the $_REQUEST['num'], which returns an array.
You may want to create a range of numbers from your $num and then do multiple LIKE's or maybe try with a REGEXP.
Use the REGEXP function in MySQL to match code to ^[0-9] which means: "the first letter must be between 0 and 9" and in ASCII, they happen to be the numbers between 0 and 9.
This will do what you want:
<?php
if (isset($_REQUEST['num'])) {
$num = explode('-', $_REQUEST['num']);
$query1 = "SELECT usercode FROM user WHERE code REGEXP '^[" . $num[0] . "-" . $num[1] . "]' ORDER BY id DESC";
$result1 = mysql_query ($query1) or die('query error');
while ($line1 = mysql_fetch_assoc($result1)) {
echo $line1['usercode'];
}
}
?>
#
cOle2 is also right about the explode function. It returns an array, the elements of which are the input string tokenized by some delimiter. In your case, $_REQUEST['num'] based on a delimiter -.

PHP Loop Detect First Instance of each Letter of MySQL results

If I query a database with PHP using MySQLi, how can I detect the first instance of each letter of the alphabet?
If I have a table like -
ID | name
1 Allen
2 John
3 Sally
4 William
and I query
SELECT * FROM table ORDER BY name ASC
Can I have something in my loop that says "if this is the first time you've seen the string in name start with the letter A", echo <a id="a"></a> to create an anchor tag? Then it will proceed to do the same for B,C,D,E,F,G, etc.. Then I can create an alphabetical legend.
Here is my query and loop:
$query = "SELECT * FROM table ORDER BY name ASC";
$result = $db->query($query);
$num = $result->num_rows;
for($i=0; $i < $num; $i++){
$row = $result->fetch_object();
//IF THIS IS THE FIRST TIME SEEING $row->name START
//WITH A DIFFERENT LETTER OF THE ALPHABET ECHO SOMETHING...
echo $row->name;
}
Create an associative array that records which letters you've seen.
$letters_seen = array();
while ($row = $result->fetch_object()) {
$letter = substr($row->name, 0, 1);
if (!isset($letters_seen[$letter])) {
// This is the first time seeing this initial letter
$letters_seen[$letter] = true;
echo "<a id='$letter'>$letter</a>";
}
echo $row->name;
}
Since your results are ordered by name, if the first letter of the current row doesn't match the first letter of the previous row, then you know it's the first time you've seen it.
$previousLetter = '';
for($i=0; $i < $num; $i++){
$row = $result->fetch_object();
if($row->name[0] != $previousLetter) {
echo "<a id='" . $row->name[0] . "'></a>";
$previousLetter = $row->name[0];
}
echo $row->name;
}

Categories