How to parse results from MySQL Table with PHP using row data? - php

Typically when I make calls into a mysql db, I reference a column for values I need. In this particular instance however, I need to retrieve a set of rows and parse with PHP accordingly. The example is this:
Table format
ID | Level
-----------------
1 | 1
2 | 2
3 | 2
4 | 3
5 | 4
6 | 4
I am ultimately trying to retrieve all possible levels and count the number of results by those levels. A simple GROUP BY, COUNT() will do the trick:
'Select Level, Count(*) as counter FROM table GROUP BY Levels ORDER BY Levels ASC'
Which will return:
table_new
Level | Count
--------------
1 | 1
2 | 2
3 | 1
4 | 2
The problem I face though is when retrieving these results with PHP, I am not quite sure how to set a variable, say 'level1' and set it to the value returned in the count column.
I assume the logic would follow:
while ($row = $stmt->fetch()) {
$count_level = $row['counter']
}
(but then I would need to create counts for each level type. Any suggestions?

$level = array();
while ($row = $stmt->fetch()) {
$level[$row['level']] = $row['counter']
}
then you have $level array and $level[1], $level[2] etc variables

Related

Display some data from row and column

I'm trying to display first and second result from table, so that user can see both results on profil.php and the date from last result. I created a view vwresult that has these fields
id | ide | name | mark | date
---+-----+---------+------+-----------
1 | 1 | trickpd | 3 | 06.01.2018
1 | 2 | trickpd | 2 | 03.01.2018
5 | 3 | trickpd | 4 | 08.01.2018
5 | 4 | trickpd | 6 | 02.01.2018
That is my table with current result, insert new data in table will show more results in view table.
This is my code
$tst = mysqli_query($mysqli, "SELECT * FROM vwresult WHERE id=$ig AND name='trickpd' ORDER BY id, date desc");
$marks = [];
while($tstx = mysqli_fetch_assoc($tst)) {
$marks[] = $tstx['mark'];
}
After that I get stuck, and can't show the results.
The goal is:
to show mark 3 and 2 and date 06.01.2018 for id 1,
and when user opens details for id 5 to see results the will see 4, and 6 and also a 08.01.2018
Please help. Thank you all for your time.
Problem is with displaying the data.. I even create a two query one to show all the data and second with limit 1,1 but after that on script it's showing random data, not first and second result like I wont.. I'm trying to display last two results and the last date of inserting the data..

need to get result of joining multiple tables as one row

I want to get result of joining multiple tables as one row and fetch multiple cuisine_name from t_cuisine table and get the cuisine_id in t_search.cuisineId column using php (CODEIGNITER) and joins
t_search table to get the cuisineId like this so that I can get the available cuisine names through the cuisineId.
t_search table
searchID|restaurant_name|cuisineId
1 | XYZ | 1,4,5
2 | KIH | 2
3 | GHY | 4,5
4 | UIO | 1,2,3
5 | RTY | 3,5
t_cuisine table
cuisineId|cuisine_name
1 | ABC
2 | CDE
3 | EFG
4 | GHZ
5 | HJL
in my Model i've used
$this->db->select('*');
$this->db->from('t_search');
$this->db->join('t_cuisine','t_cuisine.cuisineId = t_search.cuisineId');
which fetches data only based on single value in cuisineId in t_search.
$this->db->select('*');
$this->db->from('t_search');
$this->db->join('t_cuisine','t_cuisine.cuisineId IN(t_search.cuisineId)');
$this->db->where('t_cuisine.cuisineId', X);
Change X to the ID of the cuisine you are looking for
What you had previously (when your query worked based on a single value in cuisineId) was a one to many relationship. Joining like that worked well because each search had one cuisine.
This is a many to many relationship, and this table structure doesn't support it well. Instead of storing a delimited list in the cuisineId column of your t_search table, you need another table to represent the relationship between search and cuisine, like this:
t_search_cuisine table
searchID|cuisineId
1 | 1
1 | 4
1 | 5
2 | 2
3 | 4
3 | 5
4 | 1
4 | 2
4 | 3
5 | 3
5 | 5
Then you should be able to get all your data with one additional join.
$this->db->select('*');
$this->db->from('t_search');
$this->db->join('t_search_cuisine','t_search.searchID = t_search_cuisine.searchID');
$this->db->join('t_cuisine','t_search_cuisine.cuisineId = t_cuisine.cuisineId');
Based on the structure of your table, joining those table would be not easy. Perhaps you could do with two queries instead.
$this->db->select("cuisineId");
$this->where("searchID", $searchID);
$qry1 = $this->db->get("t_search");
$res1 = $qry1->row_array();
$qry1->free_result();
if ($res1) {
$this->db->select("*");
$this->db->where_in('cuisineId', $res1);
$qry2 = $this->db->get("t_cuisine");
$res2 = $qry2->result();
return ($res2) ? $res2 : false;
}

PHP + SQL -- Counting clicks in multiple rows

i stuck at the problem that my code wont count total clicks in multiple rows.
This is how the Database looks
id | jb_clicks | created_time
--------------------------------------------------
1 | 14 | 1475420816
2 | 7 | 1475422200
3 | 9 | 1475422217
4 | 3 | 1475422239
I want the result to be 33 (14+7+9+3)
How is this possible?
The current code looks like this:
SELECT COUNT(*) AS jb_clicks FROM jb_urls
my function:
function sumdatabase($select, $statement){
$config = new mysql_config;
$link = mysqli_connect($config::MYSQL_HOST,$config::MYSQL_USER,$config::MYSQL_PASS);
mysqli_select_db($link, $config::MYSQL_DATABASE);
$result = mysqli_query($link,"SELECT SUM(".$config::MYSQL_PREFIX."$select) AS jb_clicks FROM $statement");
$row = mysqli_fetch_assoc($link,$result);
return $row[$config::MYSQL_PREFIX.$select];
}
Use the following:
SELECT SUM(jb_clicks) AS jb_clicks FROM jb_urls
COUNT() is used to count the row numbers and SUM() is to calculate the total sum of a column in a table. In your case, it would be SUM(jb_clicks).

Total all occurrences of individual numbers in database table

I'm trying to total all occurrences of each individual number in a database table and return them in an associative array.
As an example, the table may consist of entries of: 1 3 4 2 1 2 1 1 4 3 3 4 2
When totaled, this would be 1 = 4, 2 = 3, 3 = 3, 4 = 3.
Ideally this would be returned as an array with keys of 'number' and 'total'.
The SQL code that you need is: SELECT num AS number, COUNT(num) AS occurrences FROM yourtable GROUP BY num
With the answer you will have at each row the num at the first field and the number of occurences at the second one. Then you can create an array and parte it just looping though the sql respones
Fetch the array would be something like(not tested code, just a guide):
$myArray = array();
while($row = mysql_fetch_array( $data ))
{
$myArray[$row["num"]] = $row["occurrences"];
}
One option is to fetch results and use array_count_values:
$arr = array_count_values($arr);
In SQL query you can do the same with COUNT and GROUP BY:
SELECT number, COUNT(*) as total FROM mytable GROUP BY number
The last will return two columns with corresponding data:
------------------
| number | total |
------------------
| 1 | 4 |
------------------
| 2 | 3 |
------------------
...

How to check of the last 2 entries of a mysql query in various column have the same value?

i have a table link with a structure like this
spreader | host1 | host2 | host 3 | id | datetime |
---------------------------------
expl.com | 1 | 5 | 2
what.de | 1 | 5 | 2
expl.com | 1 | 2 | 3
what.de | 2 | 5 | 5
How to check if the last 2 entry with the same spreader have the same values in host1, host2, host3 ...
For this example it sould give me
expl.com => host1 = 1
what.de => host2 = 5
I maybe know a way but i would have to have 10 sql querys one for each host. Do you know a efficient way to do this in php after i just get the entire date from the database with just one query?
Well i got this now it fires out 10 mysql querys i would love to see how to make this better:
global $hosters;
global $filespreader_names;
foreach ( $filespreader_names as $filespreader ) {
$feedtable = feedback_tabelle_holen(" WHERE filespreader='$filespreader' ORDER BY aktualisiert DESC LIMIT 2");
//var_dump($feedtable);
foreach ( $hosters as $host ) {
if ( ( $feedtable[0][$host] == $feedtable[1][$host] ) && ( $feedtable[0][$host] != 0 ) ) {
echo "<br />$filespreader -> $host = " . $feedtable[0][$host];
}
}
}
the globals i get in are just arrays with all the spreaders and host names i need
You might be able to do an Inner Join to produce matching records. If the gloabals you get in are from another table an inner join will give you a recordset with all the matching records that you could manipulate from there but it would only be one query.
If this is TableA on the left and TableB on the right.
id name id name
-- ---- -- ----
1 Pirate 1 Rutabaga
2 Monkey 2 Pirate
3 Ninja 3 Darth Vader
4 Spaghetti 4 Ninja
SELECT * FROM TableA
INNER JOIN TableB
ON TableA.name = TableB.name
That query will result in rows of the matching data according to your query
id name id name
-- ---- -- ----
1 Pirate 2 Pirate
3 Ninja 4 Ninja
I don't know if that helps at all but I wasn't really clear on your structure and exactly what you wanted. If the globals are session variables and not stored in a table this answer probably won't help you.
If you want to use joins check out http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Categories