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

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

Related

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;

Can i select data from mysqli database using SUBSTR to refine the query

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.

PHP - editing a string from a database

I have a column in a database which presents as the following;
< channel\01273123456:d24gf3fm >
I need to export the number from this string, the first "< channel\" is always the same, but the end ID is always unique.
I currently have the following code, but cannot think, nor find what I need to export the number.
//connection
$dbhandle = mysql_connect($hostname, $username, $password)
or die ("Unable to connect to Database");
echo "Connected\n";
//select DB
$selected = mysql_select_db("asterisk", $dbhandle)
or die("Could not select DB");
$result = mysql_query("SELECT * FROM TABLE");
while($row = mysql_fetch_array($result)) {
echo echo "channel:".$row{'channel'}."\n";
}
Hope someone could help, this is driving me crazy.
Substr seems to be the function you are seeking for:
substr and strpos.
Try something like this (depends on if you need the whole last part of the string or only the part until the ':':
$yourString = substr($row['channel'], strpos($row['channel'], '\'));
Would give you the whole substring. If you do not need the part after the the ':' you need no split yourString again from 0 to position of ':'.
$yourString2 = substr($yourString, 0, strpos($subString, ':'));
This should do the trick and as requested by tadman and it's a function :)
public function cleanMyString($string)
{
// remove channel garbage
// 01273123456:d24gf3fm >
$string = substr($string, 10, (strlen($string) - 10));
// remove space and >
// 01273123456:d24gf3fm
$string = substr($string, 0, -2);
// split on colon
// $colons[0] = 01273123456
// $colons[1] = d24gf3fm
$colons = explode(':', $string);
// first item in array is the channel
echo 'Channel: '.$colons[0].'<br><br>';
// second item is ID
echo 'ID: '.$colons[1];
}
// string, yay!
cleanMyString('< channel\\01273123456:d24gf3fm >');
have you tried these?
SELECT Right (LEFT(`your_column`, 21),11) as numbers
from asterisk
or this
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(`your_column`,'\', -1),':', 1) as numbers
from asterisk

php search in database with string

I want to search in a database with variable positions. The variables are created here:
&numbers //= user input
&naar // = user input
$number = range($numbers+1, $naar -1); //define the range between the inputs
foreach ($number as $key=>$val){
$number[$key] = $letter.$val;} //define the array
$string = implode (' ',$number); // make a string from the array
This works fine. The output is a string that contains a minimum of 0 outputs and a maximun of 7 outputs. For example: A2 A3 A4 A5
I want the database to search if something is at one of the generated positions. Ive got this already:
$query="select chess_id from stelling where positie=\"".$number."\"";
$result = mysql_query($query, $connection);
$spring = 0;
if(mysql_num_rows($result)>0)
{
$spring = mysql_result($result, 0);
}
echo "$spring";
With this code only the last generated $string output will be checked. How can i let the database check all generated string code? For example:
$string = `A2 A3 A4 A5`
$query="select chess_id from stelling where positie=\"".$number."\"";
will only check A5
sample rows from table:
wt,A1
wp,A2
wl,A3
wq,A4
Well I am not shure what exactly is your problem but why don't you use IN statement ?
$string = '(`' . implode('`, `',$number) . '`)';
$query="select chess_id from stelling where positie IN {$string}";

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