PHP - editing a string from a database - php

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

Related

Parse rows of data from string and insert into database

I am new to PHP apologize if this is an unworldly question. I am receiving a packet of data with dynamic length on the tcp/ip socket. The packet looks like this:
Palace1,radio,location1,location2,location3,location4,GSMId:Palace2,radio,location1,location2,location3,location4,GSMId:Palace3,radio,location1,location2,location3,location4,GSMId
You can see after the GSMId I have a colon to separate one reports. The length of the packet could be anything.
My task is that I want to chop this packet after every colon (:) and want to save each report in Database.
Right now what I am doing to chop each packet is:
$string = "Palace1,radio,location1,location2,location3,location4,GSMId:Palace2,radio,location1,location2,location3,location4,GSMId:Palace3,radio,location1,location2,location3,location4,GSMId";
$countString = substr_count($string, ":");
$NumberOfReports = $countString + 1;
echo $NumberOfReports."\n";
echo $countString."\n";
$chopPacket = explode(':' , $string);
foreach($chopPacket as $value)
{
$Report = $value;
echo $Report."\n";
writeToDataBase($Report);
}
DataBAse Code :
function writeToDataBase($Report)
{
date_default_timezone_set("Europe/London");
$date = date('Y-m-d H:i:s');
$counter = 0;
$DecodingData = explode("," , $Report);
if ($DecodingData > 0) {
$username = "user";
$password = "password";
$host = "localhost";
$connector = #mysql_connect($host, $username, $password) or die("Unable to connect");
$selected = #mysql_select_db("gsmdb", $connector) or die("Unable to connect");
$importSQL = "INSERT INTO gsmclient_test VALUES('".$counter."','".$DecodingData[0]."','".$DecodingData[1]."','".$DecodingData[2]."','".$DecodingData[3]."','".$DecodingData[4]."', '".$DecodingData[5]."','".$DecodingData[6]."','".$date."')";
mysql_query($importSQL) or die(mysql_error());
mysql_close($connector);
}
}
The code above is only saving the first report in database.
You will need to perform 2 separate e plosions to prepare the data.
Use a single, prepared statement to ensure that your query is stable and secure.
Here is a similar mysqli technique as a comparison.
I don't like the look of that $counter. Your database should have the row identifier as an autoincremented primary key and the date column should have a default value of CURRENT_TIMESTAMP so that that column doesn't need to be declared during insert queries.
I don't know what your column names are, so I cannot add them to my sql.
We shouldn't see mysql_ functions anymore; use mysqli_ or pdo functions.
Code:
$string = "Palace1,radio,location1,location2,location3,location4,GSMId:Palace2,radio,location1,location2,location3,location4,GSMId:Palace3,radio,location1,location2,location3,location4,GSMId";
$stmt = $mysqli->prepare("INSERT INTO gsmclient_test VALUES(?,?,?,?,?,?)";
$stmt->bind_param('ssssss', $pal, $rad, $loc1, $loc2, $loc3, $loc4);
foreach (preg_split('/,GSMId:?/', $string, -1, PREG_SPLIT_NO_EMPTY) as $rowString) {
[$pal, $rad, $loc1, $loc2, $loc3, $loc4] = explode(',', $rowString, 6);
$stmt->execute();
}

I would like to be able to generate a fill in the blank from a word missing 2 letters randomly

$word = "superman";
I would like to be able to randomly choose 2 letters from what ever word is in $word and build a fill in the blank box for me to be able to answer
example some how random picks the p and the a
su_erm_n comes up so I would fill in the first box with p and the second one with a I guess with a form
$wordfinished = "su" . $fillinblank1 . "erm" . $fillinblank2 . "n";
if ($wordfinshed == $word) {
echo "congrats";
}
else{
echo "try again";
}
I am just learning php I have some things that I have done that are very complicated but was having a hard time with the random stuff any help would help me learn this
You can use PHP's rand() function to select a random number from 0 to the length of the word you are modifying and change the character at that index to something else
For example:
$str = "superman";
$str[rand(0, strlen($str)-1)] = "_";
Assuming that the rand() function output a value of 3 for example, we'd end up with this output:
sup_rman
We can put this in a function that can be called more than once in order to make more than one blank space in the word:
function addBlank($str){
do{
$index = rand(0, strlen($str)-1);
$tmp = $str[$index];
$str[$index] = "_";
} while($tmp =! "_");
return $str;
}
This function accepts a string and after each call will replace a letter in the string with _. Each call will result in one more blank space. The variable $tmp holds the value of the string at the randomly chosen index and checks that it wasn't already a blank space, and if it was, it picks another index to try to replace.
So to put this in practice, we can call the above function multiple times and store the result back into a variable, here is example output:
$str = addBlank("superman");
//the value of $str is now sup_rman
$str = addBlank($str)
//the value of $str is now sup_r_an
$word = "superman";
$size = strlen($word) -1;
$fillinblank1 = $word[rand(0,$size)];
$fillinblank2 = $word[rand(0,$size)];
$wordfinished = "su" . $fillinblank1 . "erm" . $fillinblank2 . "n";
echo $wordfinished;
Output:
sueermun
Demo
http://ideone.com/Z66xsI

PHP. Read some characters in some strings of a file to write in database

I have a file like this:
FG 09097612 DN 6575 HL 879797
BHC 09097613 DN 6576 HL 879798
FG 09097614 DN 6577 IOPPP 879799
FG 09097614 DN 6577 IOPPP 879800
with its logic that never changes line by line, it is always the same logic.
I would create an array taking the first 2 characters as a variable "nation", then the first 8 characters as a var "prize", then 2 other characters as "player" and so on and create a record in the database for each line.
I am using this code (THE CODE IN TEH EDIT ABOVE IS CHANGED), but not being a csv with delimitation with comma or tab I don't know how to do.
ini_set("auto_detect_line_endings", 1);
$current_row = 1;
$handle = fopen("upload/import.txt", "r");
while ( ($csv_data = fgetcsv($handle, 10000, "\t") ) !== FALSE )
{
$number_of_fields = count($csv_data);
if ($current_row == 1) {
}
else {
}
fclose($handle);
}
I want to put theese var in a record of database, each var in each column.
What do you recommend?
Obviously I can not change the original txt file.
HOW TO SAVE IN DATABASE?
If I use this code (from one answer above):
$lines = file("upload/import.txt");
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$player = trim(substr($line, 12, 2)); // get 13th-14th characters as player and remove spaces
I use this code:
$dbhandle = odbc_connect("Driver={SQL Server Native Client 11.0};
Server=$myServer;Database=$myDB;", $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$query = "INSERT INTO TEST (nation) VALUES ('".$nation."')";
echo "<br>Inserted: ".$nation."<br>";
$result = odbc_exec($dbhandle, $query);
But it seems to me that this code is too heavy to be done in a foreach? Is not it?
1.In this situation, delimiter changes because of the formatting so I suggest you treat it as a string but not a csv.
FG 09097612 DN 6575 HL 879797
BHC 09097613 DN 6576 HL 879798
FG 09097614 DN 6577 IOPPP 879799
FG 09097614 DN 6577 IOPPP 879800
$lines = file("upload/import.txt");
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$player = trim(substr($line, 12, 2)); // get 13th-14th characters as player and remove spaces
}
2.Or if you insist on using csv parser, you should make consecutive spaces into one before you actually use fgetscsv:
$tempfile = "tmp/temp".microtime()."csv"; // a temp folder where you have write authority, `microtime()` here is used to generate a unique filename.
$content = file_get_contents("upload/import.txt");
while(strpos($content," ") !== false) {
// while consecutive spaces exist
$content = str_replace(" ", " ", $content);
}
file_put_contents($tempfile, $content);
Then you can treat it as a normal csv file with space delimiter like this:
$handle = fopen($tempfile, "r");
$current_row = 1;
while ( ($csv_data = fgetcsv($handle, 10000, " ") ) !== FALSE )
{
$number_of_fields = count($csv_data);
// ...
}
fclose($handle);
After you finish this , delete the temp file like this:
unlink($tempfile);
And it is better to do the insert only once than create and run the insert query in a foreach loop, so instead of adding
$query = "INSERT INTO TEST (nation) VALUES ('".$nation."')";
$result = odbc_exec($dbhandle, $query);
in each loop, which produces
INSERT INTO TEST (nation) VALUES ('FG');
INSERT INTO TEST (nation) VALUES ('BHC');
INSERT INTO TEST (nation) VALUES ('FG');
INSERT INTO TEST (nation) VALUES ('FG');
...
, it is more reasonable to create the query like this
$lines = file("upload/import.txt");
$dbhandle = odbc_connect("Driver={SQL Server Native Client 11.0};
Server=$myServer;Database=$myDB;", $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$query = "INSERT INTO TEST (nation) VALUES \n";
$row = array(); // query for each line
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$player = trim(substr($line, 12, 2)); // get 13th-14th characters as player and remove spaces
$row []= "(".$nation.")";
}
$query .= implode(",\n",$row).";";
$result = odbc_exec($dbhandle, $query);
If you echo $query, you should get something like this:
INSERT INTO TEST (nation) VALUES
('FG'),
('BHC'),
('FG'),
('FG');
which is much more light to run insert query every line.
PS: Please be careful that mysql has a limited query length. If the query is longer than max length, you will get an error , something like 'Mysql has gone away...'. I haven't much experience in using ms-sql server but there should be a same limit.
In this situation, you should split the query in a proper way. For example, run and clear the query every 10000 lines like this:
$lines = file("upload/import.txt");
$dbhandle = odbc_connect("Driver={SQL Server Native Client 11.0};
Server=$myServer;Database=$myDB;", $myUser, $myPass) or die("Couldn't connect to SQL Server on $myServer");
$query = "INSERT INTO TEST (nation) VALUES \n";
$row = array(); // query for each line
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$player = trim(substr($line, 12, 2)); // get 13th-14th characters as player and remove spaces
$row []= "('".$nation."')";
if($lineNum % 10000 == 9999){
// run and reproduce the query every 10000 lines
$query .= implode(",\n",$row).";";
// put 'echo $query;' here would help you understand the design
$result = odbc_exec($dbhandle, $query);
// It is better to check the result here if it success
// The query has been run so it should be initialized again, so is $row.
$query = "INSERT INTO TEST (nation) VALUES \n";
$row = array(); // query for each line
}
}
$query .= implode(",\n",$row).";";
$result = odbc_exec($dbhandle, $query);
Answer to 'I need now to check if in the file there are lines with the same nation, in this example "FG" and sum the $prize of each "FG" and save only the total in prize and not all the lines of FG? '
Of course you can do that, since I don't know your table or how you would like to save your other data so I will just provide a sample with only nation and price:
$lines = file("upload/import.txt");
$dbhandle = odbc_connect("Driver={SQL Server Native Client 11.0};
Server=$myServer;Database=$myDB;", $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$query = "INSERT INTO TEST (nation, prize) VALUES \n";
$row = array(); // data for each line
foreach($lines as $lineNum => $line ) {
$nation = trim(substr($line, 0, 4)); // get first four characters as nation and remove spaces
$prize = trim(substr($line, 4, 8)); // get 5th-12th characters as prize and remove spaces
$row[$nation] = !empty($row[$nation])? $row[$nation] + (int)$prize : 0 ; // make sure prize is an interger in your file
}
// Since there are not so much nations in the world, I don't think it is necessary to worry about the max query length
$query_row = array(); // query for each line
foreach($row as $nation => $sum_prize){
$query_row []= "('".$nation."','".$sum_prize."')";
}
$query .= implode(",\n",$query_row).";";
$result = odbc_exec($dbhandle, $query);
Try this:
$handle = fopen("upload/import.txt", "r");
$current_row = 1;
while(!feof($handle)){
$str=fgets($handle);//read one line of the file
$str=str_replace(" "," ",$str);//reduce all consecutive spaces to single space
$arr=explode(" ",$str);
if ($current_row == 1) {
}
else {
}
}
fclose($handle);
Now the array $arr will contain the strings {"FG","09097612,"DN","6575","HL","879797"} (after reading the first line). You can use this array to access the values and insert them in DB.
EDIT:
I understand that you want to have an array called "nation" which will contain values {"FG","BHC","FG","FG"}, and the same for prize and other variables. Try this code:
$nation=array();
$prize=array();
$player=array();
$handle = fopen("upload/import.txt", "r");
$current_row = 1;
while(!feof($handle)){
$str=fgets($handle);//read one line of the file
$str=str_replace(" "," ",$str);//reduce all consecutive spaces to single space
$arr=explode(" ",$str);
//now insert values in respective arrays
array_push($nation,$arr[0]);
array_push($prize,$arr[1]);
array_push($player,$arr[2]);
//and so on
if ($current_row == 1) {
}
else {
}
}
fclose($handle);
Now you can use the arrays $nation, $prize and $player. You can create arrays for the other values in the same manner.
Hope this helps.

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/MySQL Limiting characters outputted from a field

When I get a database array, sometimes there is fields with too much data for my results list page, which is suppose to give just a short description. How do I limit the characters count to something like 100.
This is my array for the loop:
<?php
$i = 1;
while ($row = mysql_fetch_array($result)) {
?>
This is my echo statement:
<?php echo $row['description']; ?>
You can use substr like this:
<?php echo substr($row['description'], 0, 100); ?>
But it might be better—depending on your application needs—to do the limiting when making the initial MySQL query using SUBSTR which behaves the same way, but in MySQL.
SELECT SUBSTR(example_field, 1, 100)
FROM example_table
WHERE example_field IS NOT NULL
LIMIT 1
;
That MySQL script basically means return the substring of example_field starting from the first (1) character and going 100 characters in.
This might be better in some cases since if you are limiting text length to 100 characters, why grab the data for fields that might have 1,000+ characters? That would definitely bog down your PHP script in many cases. Handling that in MySQL is the best way to nip it in the bud if your app just needs 100 characters returned.
You can try with substr()
<?php echo substr($row['description'],0,100); ?>
OR
function truncate($input, $maxWords, $maxChars)
{
$words = preg_split('/\s+/', $input);
$words = array_slice($words, 0, $maxWords);
$words = array_reverse($words);
$chars = 0;
$truncated = array();
while(count($words) > 0)
{
$fragment = trim(array_pop($words));
$chars += strlen($fragment);
if($chars > $maxChars) break;
$truncated[] = $fragment;
}
$result = implode($truncated, ' ');
return $result . ($input == $result ? '' : '...');
}
// try with cuctom function truncate() , it help to cut description by words.
<?php echo truncate($row['description'],5,200); ?>
Like the other answers, you should use substr, but you can use it in combination with strpos so that when you shorten the string, you stop after a complete word instead of interrupting a word itself.
$pos = strpos($row['description'], ' ', 100);
echo substr($row['description'], $pos);
I would do it in the SQL query. It's better to limit the results returned which reduces I/O and network throughput by not returning data from the database you're not going to use. In your SQL query do:
SELECT LEFT(description, 100) AS description
,....
FROM ...
Just in case someone is interested in another code snippets on how to limit character output with dots, I use this and it works well for me
CONCAT(SUBSTR(<column_name_here>, 1, 100),'...... Read More') AS Column_Name

Categories