i am displaying the top 5 results from a sql query using the following code;
<?php
$query = "SELECT location, COUNT(location) AS qty FROM ecmt_memberlist GROUP BY location ORDER BY qty DESC LIMIT 0,5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<span class='graphValue'>x".$row['qty']."</span> " . $row['location'] . "<br />";
} ?>
this is displaying my result strings as follows:
x46 Moon 20 - Sisters of EVE Academy
x34 Moon 7 - Ammatar Fleet Assembly Plant
x28 Jita x11 Jita IV - Moon 4 - Caldari Navy Assembly Plant
x11 Jita IV - Moon 4
x9 Lonetrek III - FUUUFAGOLAS
how can i trim down the $row['location'] to show the words before the first "-" for example;
x46 Moon 20
x34 Moon 7
x28 Jita x11 Jita IV
x11 Jita IV
x9 Lonetrek III
Just use strstr() and print before needle, e.g.
strstr($row['location'], "-", TRUE);
while you could do it with php as every on else suggest, i think its better to do it with mysql:
$query = "SELECT SUBSTRING_INDEX(location,'-',1) as location, COUNT(location) AS qty FROM ecmt_memberlist GROUP BY location ORDER BY qty DESC LIMIT 0,5";
echo explode('-', $row['location'])[0];
OR
echo preg_replace('/\-\s.+/i', '', $row['location']);
$str='x46 Moon 20 - Sisters of EVE Academy';
$str2=substr($str,0,strpos($str,' -'));
echo $str2;
There's a couple different ways you could do this, one using explode()
$location = explode("-", $row['location']);
Then call everything before the "-" with echo $location[0]; See PHP Explode
Or you can use strstr()
$location = strstr($row['location'], '-', true);
and call it with just $location as setting the 3rd parameter to true returns everything before the first occurrence of the 2nd parameter. See PHP strstr
Or you can use split()
$location = split("-", $row['location']);
and call it using $location[0]
Related
I've got a project that involves getting flight information from a database.
I want the results to look like:
01 Nov 2017 - Eastern Airways 7601
Departing from Southampton, Eastleigh (SOU) at 0840
However my code seems to bring up the below with a mysterious live of nonsense as per below
01 Nov 2017 - Eastern Airways 7601
Departing from , () at 084001 Nov 2017 - 7601 //this line I don't want
Departing from Southampton, Eastleigh (SOU) at 0840
$link = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx' );
foreach ($flights as $b) {
$query = "SELECT * FROM `airlines` WHERE `iatacode` = '$airline' LIMIT 0 , 30;";
$query .= "SELECT * FROM `airports` WHERE `Airport Code` = '$depdest' LIMIT 0 , 30;";
/* Execute queries */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_array($result))
/* print results */
{
$date=date_create($depdate);
echo "<b>" . date_format($date,"d M Y"). " - ". $row['airlinename']." ".$flightno. "</b><br/>";
echo "Departing from " .$row['City Name'].", ".$row['Airport Name']." (".$row['Airport Code'].") at " . $deptime;
}
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}
Can anyone see what I'm doing wrong?
Data base tables are as below
table 1 - Name "airports"
Airport ID City name Airport Code Airport Name Country name Country Abbrev. World Area Code
1, 108 Mile Ranch, ZMH , 108 Mile Ranch , Canada, CA, 906,
2, Aachen, AAH Aachen/Merzbruck, Germany, DE, 429,
3, Aachen, ZIU, Railway, Germany, DE, 429,
4, Aalborg, AAL, Aalborg, Denmark, DK, 419,
etc
table 2 - Name "airlines"
airline id, Iata, Airline Name
1, 0A, Amber Air,
2, 0B, Blue Air,
3, 0C, IBL Aviation,
etc
Thanks!
If I was to guess, I would say that there is a problem with the $b variable.
It seems your output is being written twice: the value "084001" in the middle of the second line looks to be the 0840 flight time from one entry, and then immediately starting the next entry as the date.
I would guess that the foreach is looping twice, instead of once, causing two outputs.
Could you do an output of the $b variable?
echo "<pre>";
print_r($b);
echo "</pre>";
I have a database with one table of two columns FirstName and LastName
and my names are Bruce Wayne, so what I want is an output that will give me this:
a 1 10%
B 1 10%
c 1 10%
e 2 20%
n 1 10%
r 1 10%
u 1 10%
W 1 10%
y 1 10%
How many times each character has occurred in both names and what is the percentage of occurrence overall.
I am new to php and mysql a little help would be welcome.
Thus far I have found this http://php.net/manual/en/function.substr-count.php
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2
I don't know if the best approach would be php or sql. Thanks!
First split all letters in an array. Count the array. Loop through the array and count how often we see them. Then loop another time to print out the result:
<?php
$text = 'This is a test';
$text = str_replace(' ', '', $text );
$arrLetters = str_split($text);
$countLetters = count($arrLetters);
$letters = [];
foreach($arrLetters as $letter){
if(isset($letters[$letter])){
$letters[$letter] += 1;
} else {
$letters[$letter] = 1;
}
}
foreach($letters as $letter => $total){
echo $letter.":".$total.":".round(($total/$countLetters*100),2)."%<br />";
}
Result:
T:1:9.09%
h:1:9.09%
i:2:18.18%
s:3:27.27%
a:1:9.09%
t:2:18.18%
e:1:9.09%
You asked:
I don't know if the best approach would be php or sql.
For this character-frequency application, you should fetch the strings with a MySQL query and count their frequencies in your php client side language.
You could work out some MySQL code to do the counts server side, but it will be quite complex.
I do not understand something! I want to create a query ... in the database under the following entry field stamp_updated, 2014-01-28 17:31:02.
Now I just want to have records with the tag 28:
$ qry = "SELECT SUM (bytes) AS total FROM acct_v4 WHERE SUBSTRING (stamp_updated, 9,10) = '28 '";
Unfortunately, I get no output, it's the SUBSTRING?
PS:
What is supposed to be: I logged the port traffic, let him write in a database and would like to have daily statistics.
done ask new
Now I stand in front of logig proplem ... how do I put it best when I try to spend as Everyday Traffic?
2014-01-26: xx traffic 2014-01-27: xx traffic 2014-01-28: xx traffic
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<?php
function formatBytes($size, $precision = 2)
{
$base = log($size) / log(1024);
$suffixes = array('', 'k', 'MB', 'GB', 'TB');
return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}
$db=mysql_connect("localhost","traffic",".....");
mysql_select_db("traffic",$db);
$qry = "SELECT SUM(bytes) AS total FROM acct_v4
WHERE SUBSTRING(stamp_updated,9,2) = '28' ";
$select = mysql_query($qry);
$result = mysql_fetch_array($select);
echo 'Summe: '.formatBytes($result['total']);
//echo $result['total'];
?>
You can try
SELECT SUM (bytes) AS total FROM acct_v4 WHERE DAY(stamp_updated) = 28;
your SUBSTRING (stamp_updated, 9,10) will return 10 charcters after the position 9
--> 28 17:31:0
this is the basic of SUBSTRING
SUBSTRING(str, pos, len)
so in your case you should just change 10 to 2 like that
SUBSTRING (stamp_updated, 9,2)
and it will work
your whole query will be
$ qry = "SELECT SUM(bytes) AS total FROM acct_v4
WHERE SUBSTRING(stamp_updated,9,2) = '28' ";
Without seeing your SHOW CREATE TABLE, it looks as though you are after dates with 28 for the day. You should use MySQL's DAY function. This assumes that stamp_updated is a proper DATE or DATETIME field.
$qry = "SELECT SUM (bytes) AS total FROM acct_v4 WHERE DAY(stamp_updated) = 28";
I made a simple query system through mySQL which is showing me 100 records and I fetch them into my game but I have probelm with the codes in PHP.
I want to have 5char space between each row So I have to use tab space (\t\t\t\t\t), But I have a problem with this current system (e.g If I have field with two diffrent string value 10char and 2char then use tab space to make space between them I get different results:
2Char string + 5char space = 7Char and 10Char string + 5Char space = 15Char
$query = "SELECT * FROM `scores` ORDER by `score` DESC LIMIT 100";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$num_results = mysql_num_rows($result);
for($i = 0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
echo $i+1 . "-" . "\t\t Name: " .$row['name'] . "\t\t\t\t Device: " . $row['device'] . "\n \t\t Difficulty: " . $row['level']. "\t\t\t\t Score: " . $row['score'] . "\n\n";
}
Codes Output
1- Name: James Device: HTC OneX
Difficulty: Hard Score: 5760
2- Name: Erika_S Device: PC
Difficulty: Normal Score: 13780
...
My Desired Output
1- Name: James Device: HTC OneX
Difficulty: Hard Score: 5760
2- Name: Erika_S Device: PC
Difficulty: Normal Score: 13780
...
Tab in fact is one char, but displayed in the way that user want. When, for example, in IDE you choose 8 spaces for 1 tab you will get it. There's a fantastic concept called elastic tabstops, but it's only concept - so sad.
Conclusion: you can't do it what you described with tab.
What you can do:
Calculate needed spaces and hardcode with , but it's dirty and you shouldn't do this.
Use html tables
Instead of $row['...'] use sprintf("%-15s", $row['...']), but in each place you'll need to adjust the number (-15) to what's really needed
<?php
$s = 'monkey';
$t = 'many monkeys';
printf("[%s]\n", $s); // standard string output
printf("[%10s]\n", $s); // right-justification with spaces
printf("[%-10s]\n", $s); // left-justification with spaces
printf("[%010s]\n", $s); // zero-padding works on strings too
printf("[%'#10s]\n", $s); // use the custom padding character '#'
printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters
?>
The above example will output:
[monkey]
[ monkey]
[monkey ]
[0000monkey]
[####monkey]
[many monke]
read more at http://www.php.net/manual/en/function.sprintf.php
if you can't use printf, you can easily create your own function that does something similar, and is enough for what you need:
function add_spaces($str, $total_len) {
return $str . substr(" ", 0, $total_len - strlen($str));
}
I have a script which takes in some user input, cleans it and tries to replace the value in a string. I found that the str replace that I use cant seem to match e.g. 11 +tum. Why is that? Can I fix it some way? Does preg replace manage it, and if so how does that look in preg replace?
Function
The script prepares the user input string for a full text query, all words are mandatory so each space is replaced with space+. But some phrases like 11 tumneed to be searchable and thus put in double quotes. The failing part is that the scirpt cant seem to match some phrases even though echoing the valus before comparison shows they are the same, e.g. 11 tum
Code:
//processedQuery e.g. 'laptop 11 tum'
$processedQuery = str_replace(" "," +",$processedQuery);
echo processedQuery; //parses laptop +11 +tum
foreach($commonQuery as $value){ //$commonQuery = array("11 tum", "13 tum", "15 tum", "17 tum", "asus eee", "asus 1005","asus 1010")
//compile : simulated query format error
$simulatedErrorValue = str_replace(" "," +",$value);
echo simulatedErrorValue; //parses 11 +tum
$processedQuery = str_replace($simulatedErrorValue,'"'.$value.'"',$processedQuery);
}
echo $processedQuery; //parses laptop +11 +tum
//exchange 11 tum for asus eee (the other commonQuery and the last echo of $processedQuery shows the correct laptop +"asus eee"
You are confusing the input to your function. I'm getting the desired result with a small modification:
11 +tum
laptop +"11 tum"
asus +eee
laptop +"11 tum"
Your error is this line:
$commonQuery = array("11 tum, asus eee")
This is an array with just 1 member.
You want to change the array to have 2 members:
$commonQuery = array("11 tum" , "asus eee");
Here is my full code:
<?php
$processedQuery = 'laptop 11 tum';
$processedQuery = str_replace(" "," +",$processedQuery);
$commonQuery = array("11 tum" , "asus eee");
foreach ( $commonQuery as $value ) { //$commonQuery = array("11 tum, asus eee")
//compile : simulated query format error
$simulatedErrorValue = str_replace(" "," +",$value);
echo "$simulatedErrorValue\n"; //parses 11 +tum
$processedQuery = str_replace($simulatedErrorValue,'"'.$value.'"',$processedQuery);
echo "$processedQuery\n";
}
?>