How to use $row results into mysqli_query? - php

How can I use $row results into a mysqli_query?
$result1 = mysqli_query($connect,"SELECT subcat_ID FROM subcategories WHERE cat_ID=$cat_ID");
$row=mysqli_fetch_array($result1);
$result2 = mysqli_query($connect,"SELECT subsubcat_name FROM subsubcategories WHERE subcat_ID='".$row['subcat_ID']."'");
while ($row = mysqli_fetch_array($result2)){
if (isset($row)){
echo $row['subsubcat_name'];
echo "<br>";
}
I don't get any error but I can't get it printed.
Any idea what I'm doing wrong?
Thanks for any help!
==================================================================================
1st edit
Because my problem isn't solved yet, I'm explaining it a bit more in depth:
My databases:
- categories: cat_ID, cat_name
- subcategories: subcat_ID, cat_ID, extra_cat_ID, subcat_name
- subsubcategories: subsubcat_ID, subcat_ID, subsubcat_name
At a certain point I get the value of a cat_ID (categories) through an url.
What I want to do is wherever cat_id of categories is the same value as the cat_id or extra_cat_ID like in subcategories (I also want to be able to print subcat_name), where subcat_ID of subcategories is the same as subcat_ID of subsubcategories ---> print subsubcat_name.
Categories
-------------------------
cat_ID | cat_name
------------------
4 | Baby & Kids
5 | Bicycles
6 | Boats
7 | Books & Comics
....
13 | Clothes & Accessories
....
35 | Sport & Fitness
36 | Study
....
38 | Toys & Games
....
Subcategories
-------------------------
subcat_ID | cat_ID | extra_cat_ID | subcat_name
------------------------------------------------
....
15 | 4 | 13 | Baby clothes
16 | 4 | 0 | Baby products
17 | 4 | 13 | Kids clothes
18 | 4 | 38 | Toys
19 | 5 | 0 | Bycicles
20 | 5 | 0 | Bycicle gear & Accessories
21 | 6 | 0 | Boat parts
22 | 6 | 0 | Other Boats
23 | 6 | 0 | Power Boats
24 | 6 | 0 | Sailboats
25 | 6 | 35 | Windsurf & Surfing
26 | 7 | 0 | Antiquarian
27 | 7 | 0 | Books
28 | 7 | 38 | Childrens books
29 | 7 | 0 | Comics
30 | 7 | 0 | Magazines & Newspapers
31 | 7 | 36 | Study & Training
Subsubcategories
-------------------------
subsubcat_ID | subcat_ID | subsubcat_name
-----------------------------------------
...
470 | 15 | Baptism outfits
471 | 15 | Bibs
472 | 15 | Body warmers
473 | 15 | Bodysuits
....
496 | 16 | Baby bath
497 | 16 | Baby books
498 | 16 | Baby inserts
499 | 16 | Baby monitors
....
548 | 17 | Belts
549 | 17 | Blouses & Shirts
550 | 17 | Body warmer
551 | 17 | Boots
....
....
740 | 26 | Music
741 | 26 | Navy
742 | 26 | Novel
743 | 26 | Photography
....
....
867 | 30 | Animals
868 | 30 | Arts and Culture
869 | 30 | Branch
870 | 30 | Cars
870 | 30 | Computers
....
....
etc.
I hope this clearout things a bit more.

Instead of running two queries you should use a JOIN.
For example this $query :
SELECT subcategories.cat_ID, subsubcategories.subsubcat_name
FROM subcategories
INNER JOIN subsubcategories
ON subcategories.cat_ID=subsubcategories.subcat_ID
WHERE subcategories.cat_ID = ?
Preparing your query is more appropriate/safe in this case:
/* create a prepared statement */
if ($result = mysqli_prepare($connect, $query)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($result, "i", $cat_ID);
/* execute query */
mysqli_stmt_execute($result);
/* fetch data */
while ($row = mysqli_fetch_array($result)){
if (isset($row)){
echo $row['subsubcat_name'];
echo "<br>";
}
}
}
DEMO for SQL JOIN
Got it working. This is the code I used:
$result=mysqli_query($connect,"SELECT subcategories.cat_ID, subsubcategories.subsubcat_name FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subcategories.cat_ID = $cat_ID OR subcategories.extra_cat_ID = $cat_ID");
while ($row = mysqli_fetch_array($result)){
echo $row['subsubcat_name'];
echo "<br>";
}
Though not sure it is the safe way to do it. Suggestions are always welcome.
Thanks to meda to showing me another approach tho it is not quite the same code.

Here is an example on how to use mysqli
object oriented
<?php
$connect= new mysqli("localhost","user","passwd","database");
if ($connect->connect_errno){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = $connect->query($select)){
while($row = $result->fetch_object()){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
$connect->close();
?>
Procedural Style
<?php
$connect= mysqli_connect("localhost","user","passwd","database");
if (mysqli_connect_errno()){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = mysqli_query($connect,$select)){
while($row = mysqli_fetch_object($result)){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
mysqli_close($connect);
?>

Related

Selecting max of sum of rows

I have a table in the database like this:
student_id | subject_id | get_ca1 | get_ca2 | get_exam
----------------------------------------------------------
101 | 1 | 10 | 7 | 10
102 | 2 | 5 | 5 | 10
103 | 1 | 9 | 10 | 4
101 | 1 | 8 | 10 | 10
103 | 2 | 2 | 10 | 10
104 | 1 | 7 | 8 | 5
101 | 2 | 7 | 8 | 5
I want to get the highest score of a student in a subject. But first, I would have to sum up the rows get_ca1 + get_ca2....+ get_exam to another column to get the total scores of each student in a particular subject.
Then I want to get the Max score from the total. This means;
the highest score in subject_id = 1 is 28 gotten by student_id=101
the highest score in subject_id = 2 is 22 by student_id = 103
So far, this is my query:
SELECT MAX(`get_ca1`+`get_ca2`+`get_exam`)
AS max_score
FROM exam_results WHERE `subject_id`=1
This outputs 28.
Now, this is how I want my table in view to look:
For student_id= 103
subject | ca1 | ca2 | exam | highest
----------------------------------------
Maths | 9 | 10 | 4 | 28
Eng | 2 | 10 | 10 | 22
This is where my problem lies. I tried putting the code directly in the view file like this:
<td>
<?php
$query = $this->db->query("SELECT MAX(`get_ca1`+`get_ca2`+`get_exam`)
AS max_score FROM exam_results WHERE `subjects.id`=1");
$highscore = $query->row();
echo $highscore->max_score;
?>
</td>
It outputs 28 correctly. However, it shows 28 in all the subjects. I'm guessing is because of this WHERE `subjects.id`=1"
If I'm to go by this method, how do I get the highest scores to show in each subject column?
is it WHERE `subjects.id`=.'"$subject_id"`"?
But I would prefer the MVC method which I'm not so familiar with.
so far...
Model
public function GetMaxScore($subject_id)
{
$this->db->select_max('`get_ca1`+`get_ca2`+`get_exam` AS max_score');
$this->db->where('subject_id', $subject_id);
return $this->db->get('max_score')->row();
}
Controller:
public function GetMaxScore($subject_id)
{
$data = $this->examgroupstudent_model->GetMaxScore($subject_id);
return $data->max_score;
}
If this is correct by any means, how do I output it in my view?

Query SUM for two fields in two different tables PHP

I am having a problem generating the result I need. I want to sum the other table gg_hp base on gg_id
+--------------+----------+-------+------------+
| sg_name | sg_grade | gg_id | subject_id |
+--------------+----------+-------+------------+
| Quiz 1 | 20 | 14 | 68 |
| Midterm Exam | 50 | 15 | 68 |
| Quiz 2 | 50 | 14 | 68 |
+-------+--------------+----------+-------+----+
tbl_gradesubcateg
+-------+--------------+------------+------------+------------+------------+-------+
| gg_id | categname | percentage | gradecount | teacher_id | subject_id | gg_hp |
+-------+--------------+------------+------------+------------+------------+-------+
| 14 | Quiz | 10 | NULL | 4 | 68 | 0 |
| 15 | Midterm Exam | 20 | NULL | 4 | 68 | 0 |
+-------+--------------+------------+------------+------------+------------+-------+
This is my expected output
+-------+--------------+------------+------------+------------+------------+-------+
| gg_id | categname | percentage | gradecount | teacher_id | subject_id | gg_hp |
+-------+--------------+------------+------------+------------+------------+-------+
| 14 | Quiz | 10 | NULL | 4 | 68 | 70 |
| 15 | Midterm Exam | 20 | NULL | 4 | 68 | 50 |
+-------+--------------+------------+------------+------------+------------+-------+
This is the query I made but.. Im not getting accurate result.
$querycount = "SELECT * FROM tbl_gradesubcateg order by gg_id asc ";
$query_run = mysqli_query($con,$querycount);
$sums= 0;
$ctr = 0;
$id1 = "";
while ($num = mysqli_fetch_assoc ($query_run)) {
$sums += $num['sg_grade'];
$id= $num['gg_id'];
if($id == $id1)
{
$queryhp = mysqli_query($con,"UPDATE tbl_gradecateg SET gg_hp = '".$sums."' where gg_id='".$id."'") or die(mysqli_error($con));
}
else
{
$queryhp = mysqli_query($con,"UPDATE tbl_gradecateg SET gg_hp = '".$sums."' where gg_id='".$id."'") or die(mysqli_error($con));
$sums= 0;
}
$id1= $num['gg_id'];
}
```
Any thoughts would be great.
A correlated subquery is a simple approach:
update tbl_gradesubcateg gs
set sg_grade = (select sum(sg.g_grade)
from gg_hp g
where g.gg_id = gs.gg_id
);
I don't recommend doing this calculation, though. It is simple enough to aggregate when you query the table. Summarizing the results just means that they are out-of-date the next time rows are inserted, updated, or deleted in the tables.

Fetching/Putting 2 variables in a mysqli_num_row and mysqli_fetch_array in PHP

Basically I want to do a search by category and title. My problem is that the two are located in separate tables. I was thinking of putting 2 variables in the mysqli_num_rows or mysqli_fetch_array but I don't think it's the right idea. The $search variable is working already but I don't know what I will do for $searchcat that is a different table.
<table border="1">
<tr>
<th>ID</th>
<th>Survey Title</th>
<th>Category</th>
</tr>
<?php
if (isset($_POST['submit']))
{
include 'testdb.php'; //connection is written in other page (db.php)
$var =$_POST['search'] ;
$searchtype = $_POST['searchtype'];
$my_query="SELECT s.survey_id, s.title,c.categoryname
FROM survey_header as sh
JOIN survey AS s ON sh.survey_id=s.survey_id
JOIN category AS c ON sh.category_id=c.category_id
WHERE $searchtype LIKE '%".$var."%'
ORDER BY title ASC";
$get_data= mysqli_query($con, $my_query) or die ("Couldn't execute query: ".mysqli_error());
if (mysqli_num_rows($get_data) > 0 )
{
echo "<h3>Search results:</h3>";
while($show = mysqli_fetch_array($get_data))
{
$id = $show['survey_id'];
$title = $show['title'];
$category = $show['categoryname']; //
echo "<tr align='center'>";
echo "<td><font color='black'>" .$id. "</font></td>";
echo "<td><font color='black'>" .$title. "</font></td>";
echo "<td><font color='black'>" .$category. "</font></td>";
}
}
else{
echo "No Records found!";
}
}
?>
</table>
</body>
This is table category (categoryname is what I need)
+-------------+---------------+-------------+
| category_id | categoryname | datecreated |
| 1 | Philosophical | |
| 4 | Political | |
| 6 | Social | |
This is table survey (title is all I need)
| 1 | survey_id | title | description | duration | gender | age_group_from | age_group_to |
| 2 | 44 | game1 | description1 | 5 | male | 0 | 18 |
| 3 | 45 | game2 | description2 | 25 | female | 18 | 25 |
| 4 | 46 | game3 | description3 | 89 | female | 26 | 35 |
This is table survey_header (survey_id and category_id is what I need)
| 1 | survey_id | date_created | date_updated | opening_date | closing_date | category_id | topic_id |
| 2 | 33 | Not important | Not important | NULL | NULL | 1 | NULL |
| 3 | 45 | Not important | Not important | NULL | NULL | 6 | NULL |
| 4 | 46 | Not important | Not important | NULL | NULL | 4 | NULL |
Try this query :
$my_query="SELECT s.survey_id, s.title,c.categoryname
FROM survey_header as sh
JOIN survey AS s ON sh.survey_id=s.survey_id
JOIN category AS c ON sh.category_id=c.category_id
WHERE $searchtype LIKE '%".$var."%'
ORDER BY title ASC";
$get_data= mysqli_query($con, $my_query) or die ("Couldn't execute query: ".mysqli_error());
if (mysqli_num_rows($get_data) > 0 )
{
/*create table*/
}
else
// do something else

function SQL SUM query

I have a table with numbers like this:
______________________________________
| axle_id | train_id | axle | distance |
|_________|__________|______|__________|
| 1 | 1 | 1 | 20 |
| 2 | 1 | 2 | 50 |
| 3 | 1 | 3 | 200 |
| 4 | 1 | 4 | 50 |
| 5 | 1 | 5 | 200 |
| 6 | 1 | 6 | 50 |
| 7 | 1 | 7 | 200 |
| 8 | 1 | 8 | 50 |
|_________|__________|______|__________|
Now i want to count them and make a calculation with SUM.
The code i have right now:
function count_axles($id) {
$sql = "SELECT sum(distance)/(25000)*(100) as totaldistance from axle WHERE train_id = :train_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":train_id", $id, PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}
And i call this function via:
<?php
$count_axle = $database->count_axles($_GET['train_id']);
?>
<?php
foreach($count_axle as $counting){
}
echo $counting['totaldistance'];
?>
Now the output is correct.
(3.2800000000000002) This is the percentage of 25.000
But i want to add 5000 like:
$sql = "SELECT sum(distance)+(5000)/(25000)*(100) as totaldistance from axle WHERE train_id = :train_id";
But when i do that, the output generates something randomly like:
840
Why does it do this, and how do i solve this?
Basic math. You're doing
5000
sum(distance) + --------------
25000 * 100
when you really want
sum(distance) + 5000
------------------------
25000 * 100
Try
SELECT (sum(distance)+(5000))/(25000)*(100)
^--------------------^
instead. Note the extra brackets.
And remember the old BEDMAS mnemonic: brackets, exponents, division, multiplication, addition, subtraction...
Try with:
$sql = "SELECT (sum(distance)+(5000))/(25000)*(100) as totaldistance from axle WHERE train_id = :train_id";
Division has preference over sum operations.

Displaying number of items per category in PHP

I'm new to PHP/MYSQL languages and would like to know if anyone could tell me how to display number of items next to the categories I have given below.
Example,
Art (5)
Drama (2)
Music (5)
Fiction (4)
Computer (5)
And, here is my php code;
index.php
<?php
$dbh=mysql_connect("localhost","root","root") or die ('Cannot connedt to the Database' .mysql_errno());
mysql_select_db("booksdb");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Select a Company</title>
</head>
<body>
<?php
$res_query = mysql_query("SELECT * FROM bookcatname ORDER BY category ASC");
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['category'].'<br />';
}
?>
</body>
</html>
page.php
<?php
$dbh=mysql_connect("localhost","root","root") or die ('Cannot connect to the Database' .mysql_errno());
mysql_select_db("booksdb");
if ( empty($_GET['cat_id']) )
{
header('Location: index.php');
exit();
}
$getCats = mysql_query("SELECT * FROM books WHERE cat_id = '".intval($_GET['cat_id'])."'");
echo '<ul>';
while ( $book = mysql_fetch_assoc($getCats) )
{
echo '<li>'.$book['title'].'<br />'.$book['author'].'<br />'.'</li><br />';
}
echo '</ul>';
?>
Here are the tables;
table name - bookcatname
+----+--------+----------+
| id | cat_id | category |
+----+--------+----------+
| 1 | 1 | Art |
| 2 | 2 | Drama |
| 3 | 3 | Music |
| 4 | 4 | Fiction |
| 5 | 5 | Computer |
+----+--------+----------+
table name - books
+----+--------+---------------------------------+-----------------------+
| id | cat_id | title | author |
+----+--------+---------------------------------+-----------------------+
| 1 | 1 | Color and Light | James Gurney |
| 2 | 1 | The Art Spirit | Robert Henry |
| 3 | 1 | Art & Fear | David Bayles |
| 4 | 1 | How Pictures Work | Molly Bang |
| 5 | 1 | Imaginative Realism | James Gurney |
| 6 | 2 | A Walk To Remember | Nicholas Sparks |
| 7 | 2 | An Old Fashioned Girl | Louisa May Alcott |
| 8 | 3 | The Rest Is Noise | Alex Ross |
| 9 | 3 | It Still Moves | Amanda Petrusich |
| 10 | 3 | Chronicles | Bob Dylan |
| 11 | 3 | Dream Boogie | Peter Guralnick |
| 12 | 3 | Escaping The Delta | Robert Johnson |
| 13 | 4 | Atlas Shrugged | Ayn Rand |
| 14 | 4 | Anthem | Ayn Rand |
| 15 | 4 | Sons and Lovers | D.H. Lawrence |
| 16 | 4 | Henderson the Rain King | Saul Bellow |
| 17 | 5 | The Art of Computer Programming | Donald Knuth |
| 18 | 5 | The Art of Unix Programming | Eric Raymond |
| 19 | 5 | Free Software, Free Society | Richard M. Stallman |
| 20 | 5 | Database System Concepts | Abraham Silberschatz |
| 21 | 5 | 3ds Max 2008 in Simple Steps | Kognet Solutions Inc. |
+----+--------+---------------------------------+-----------------------+
SELECT A.cat_id as cat_id, count(A.cat_id) as cnt, B.category as cat_name
FROM books A, bookcatname B
WHERE A.cat_id=B.cat_id
GROUP BY A.cat_id
UPDATE 2 :
<?php
$sql = "SELECT A.cat_id as cat_id, count(A.cat_id) as cnt, B.category as cat_name
FROM books A, bookcatname B
WHERE A.cat_id=B.cat_id
GROUP BY A.cat_id";
$res_query = mysql_query($sql);
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['cat_name'].'<br />';
}
?>
I don't want to complicate things since you are starting to learn PHP and MySQL. There are a lot of ways to achieve what you want but I will hand you a simple solution with your problem.
You can try changing your code from:
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['category'].'<br />';
}
To:
while($category = mysql_fetch_assoc($res_query))
{
$categoryID = $category['cat_id'];
$queryCount = mysql_query("SELECT COUNT(id) AS total
FROM books
WHERE cat_id = '$categoryID'");
$row = mysql_fetch_assoc($queryCount);
echo '' . $category['category'] . ' (' . $row['total'] . ')<br />';
// Note: Please try to var_dump($row) and look if $row['total'] contains the number of books under on that category.
}
That's all and Enjoy learning...
You need to use JOIN opertaion on tables "bookcatname" and "books" to get the total count for each category.
SELECT A.cat_id as cat_id, count(A.cat_id) as cnt, B.category as cat_name
FROM books A, bookcatname B
WHERE A.cat_id=B.cat_id
GROUP BY A.cat_id
Check demo on : http://sqlfiddle.com/#!2/73eb29/13
Modify your following part of index.php file:
$res_query = mysql_query("SELECT A.cat_id as cat_id, count(A.cat_id) as cnt, B.category as cat_name FROM books A, bookcatname B WHERE A.cat_id=B.cat_id GROUP BY A.cat_id");
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['category'].'('.$category['cnt'].')<br />';
}
Try using SQL code that will count and group the items.
I am sure this code will work but it is UN-TESTED.
SELECT COUNT(*) as cnt,category
FROM books
LEFT JOIN bookcatname ON books.cat_id = bookcatname.cat_id
GROUP BY category
Then in your php code you will use something like this:
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['category'].'('.$category['cnt'].')<br />';
}
EDIT
You will add this code to where you load the categories.

Categories