Simple and Efficient Code to Count Data in PHP with MySQL - php

So I think there's will be a simple and efficient code to count data with PHP and get the data output from different MySQL tables. This implementation is used to display how much data in my dashboard page.
But I prefer to use PHP procedural style because I'm still learning.
So here is my dirty code:
$count_admin = mysqli_query($conn, "SELECT COUNT(*) AS count_admin FROM employee WHERE level_id = 1");
$count_officer = mysqli_query($conn, "SELECT COUNT(*) AS count_officer FROM employee WHERE level_id = 2");
$count_goods = mysqli_query($conn, "SELECT COUNT(*) AS count_goods FROM goods");
$count_customer = mysqli_query($conn, "SELECT COUNT(*) AS count_customer FROM customer");
$row_admin = mysqli_fetch_assoc($count_admin);
$row_officer = mysqli_fetch_assoc($count_officer);
$row_goods = mysqli_fetch_assoc($count_goods);
$row_customer = mysqli_fetch_assoc($count_customer);
echo $row_admin['count_admin'];
echo $row_officer['count_officer'];
echo $row_goods['count_goods'];
echo $row_customer['count_customer'];

Related

How to output all data from multiple tables using mysqli php

Most of the variables will be in my language sorry about that. Also keep in mind i have very little knowledge of php/mysql as even my schools teachers have no idea what is it.
In my database there are 4 tables. The tables only have primary keys. The tables do not have any foreign key or references to other tables.
This is because in my school project we were told to not add foreign key and references. This means I cant/dont know how to use JOIN.
Currently i am attempting to output all of the data from the 4 tables and output them as 1 using html/css.
My main problem is i do not know how to output data from different rows.
I have tried using mysqli_data_seek to select each row with my counter($no) but it seems that either im using it wrong or its just not supposed to do that.
I have also tried using mysqli_fetch_assoc but i still get the same output.
I have a connection to my database
This is the code mysqli_data_seek
<?php
$row = mysqli_query($connection, "SELECT Kod_Barang, Kod_Rak, Harga, Tarikh_Jual from stok");
$no = 0;
if (mysqli_num_rows($row) > 0) {
while ($stok = mysqli_fetch_assoc($row)) {
$stok = mysqli_query($connection, "SELECT Kod_Barang, Kod_Rak, Harga, Tarikh_Jual from stok");
$datastok = mysqli_data_seek($stok, $no);
//get data from "barang' table
$barang = mysqli_query($connection, "SELECT Nama_Barang, no_Barang from barang");
$databarang = mysqli_data_seek($barang, $no);
//get data from "lokasi"
$lokasi = mysqli_query($connection, "SELECT Jenis_Barang from lokasi");
$datalokasi = mysqli_data_seek($lokasi, $no);
//get data from "tarikh" table
$tarikh = mysqli_query($connection, "SELECT Tarikh_Beli from tarikh");
$datatarikh = mysqli_data_seek($tarikh, $no);
$no++;
then after this i will have a output which is connected to a table already made (this is still in the while loop)
echo '<tr>';
echo '<td>'.$no.' </td>';
echo '<td>'.$datastok.'</td>';
echo '<td>'.$databarang.'</td>';
echo '<td>'.$datalokasi.'</td>';
echo '<td>'.$datastok.'</td>';
echo '<tr>';
This is the code with mysqli_fetch_assoc
<?php
$rowstok = mysqli_query($connection, "SELECT Kod_Barang, Kod_Rak, Harga, Tarikh_Jual from stok");
$no = 0;
if (mysqli_num_rows($rowstok)> 0) {
while ($stok = mysqli_fetch_assoc($rowstok)) {
$stok = mysqli_query($connection, "SELECT Kod_Barang, Kod_Rak, Harga, Tarikh_Jual from stok");
$datastok = mysqli_fetch_assoc($stok);
//get data from "barang" table
$barang = mysqli_query($connection, "SELECT Nama_Barang, Bil_Barang from barang");
$databarang = mysqli_fetch_assoc($barang);
//get data from "lokasi" table
$lokasi = mysqli_query($connection, "SELECT Jenis_Barang from lokasi");
$datalokasi = mysqli_fetch_assoc($lokasi);
//get data from "tarikh" table
$tarikh = mysqli_query($connection, "SELECT Tarikh_Beli from tarikh");
$datatarikh = mysqli_fetch_assoc($tarikh);
$no++;
Again here is my output table
//output table
echo '<tr>';
echo '<td>'.$no.' </td>';
echo '<td>'.$datastok['Kod_Barang'].'</td>';
echo '<td>'.$databarang['Nama_Barang'].'</td>';
echo '<td>'.$datalokasi['Jenis_Barang'].'</td>';
echo '<td>'.$datastok['Harga'].'</td>';
echo '<tr>';
Right now the output is just showing the first's rows data multiple times based on number of row. And also my counter($no) in increasing by 2 (1,3,5,7,....) not as expected 1
I am trying to get it to be each rows data.
I got the answer thanks to #ADyson.
I just changed my long line of code to JOIN
$data = mysqli_query($connection , "SELECT *
FROM stok
INNER JOIN barang
ON stok.Kod_Barang=barang.Kod_Barang
INNER JOIN lokasi
ON stok.Kod_Rak=lokasi.Kod_Rak
INNER JOIN tarikh
ON barang.Nama_Barang=tarikh.Nama_Barang");
again sorry for non English attributes.
here is where i learnt JOIN from another question
SQL Inner join more than two tables

Using variable with multiple values in MySQL LIKE clause

can someone help me on the proper way of using a variable with multiple values in MySQL LIKE clause?
by the way, I have two tables teacher and student.
Teacher table contains. (fname,lname,subject,yr,sec) columns and for the student table (lrn,yr,sec)
what I'm trying to achieve is to count the total number of students of the teacher from all sections.
Here's my query for getting teacher's sections:
<?php
$result= mysqli_query($con, "select *from teacher where lname
= 'Uy' and subject = 'Science & Technology 7'" );
while($rowx = mysqli_fetch_array($result)) {
$section = $rowx['sec'];
}
?>
echoing $section output this: Our Lady of FatimaOur Lady of Guadalupe
Heres my query to count the students.
<?php
$ratequery = mysqli_query($con, "SELECT *,
(SELECT COUNT(*) FROM student WHERE
sec LIKE '%$section%') AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
?>
Output: the count works but only the first value [Our Lady of Fatima] of $section is getting recognized by LIKE clause, so only 1 section is getting counted.
by the way, sorry for my bad English and explanation.
Use Section as a input for second query:
<?php
$final_result = array();
$result= mysqli_query($con, "select *from teacher where lname
= 'Uy' and subject = 'Science & Technology 7'" );
while($rowx = mysqli_fetch_array($result))
{
$section = $rowx['sec'];
$ratequery = mysqli_query($con, "SELECT *, (SELECT COUNT(*) FROM student WHERE
sec =$section) AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
array_push($final_result,array("section"=>$section,"rateresult"=>$rateresult));
}
var_dump($final_result); // Display section wise data
?>
somehow I have managed to achieve my goal it but in other way . I used WHERE IN clause instead of LIKE clause. stored my query results into an array.. then used implode to add seperator.
Thanks for the help mr. #ashnu
<?php
$query="$con, select *from teacher where lname = 'Uy' and subject = 'Science & Technology 7'";
$result = mysqli_query($query) or die;
$sections = array();
while($row = mysqli_fetch_assoc($result))
{
$sections[] = $row['sec'];
}
$string = implode("','",$sections)
?>
<?php
$ratequery = mysqli_query($con, "SELECT *,
(SELECT COUNT(*) FROM student WHERE sec IN ('$string')) AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
?>

Do I need a left, natural or simple join in SQL?

I am new to PHP coding and just trying to fix some functionality on my site that was left over from the lead developer.
The site, [Vloggi], is a marketplace. So I need to show the name of the job poster in the assignments page . The table I have the jobs in only has the ID, not the name.
So I need a join, but I've tried and it breaks the entire site.
The SQL has 17 tables, I need to display the User Name (usr_name) contained in table 3, the organisation contained in table 7 (usrg_orgname) with the job posting user (vlop_usr_id) details in table 14.
The primary key is users.usr_id, which is linked to users_gor.usrg_usr_id and vlog-ops.vlog_usr_id.
Table 3: users
usr_id, usr_email, usr_password, usr_fbuser, usr_fbtoken, usr_name, usr_loc_name, usr_loc_lat1, usr_loc_lon1, usr_loc_lat2, usr_loc_lon2, usr_status, usr_gor, usr_vgr, usr_token, usr_regtoken,
table 7: users_gor
usrg_usr_id, usrg_creditops, usrg_creditvlog, usrg_creditvlogette, usrg_destination, usrg_orgname, usrg_orgtype, usrg_location, usrg_website, usrg_jobtitle, usrg_phone, usrg_address1, usrg_address2, usrg_state, usrg_postcode, usrg_country
Table 14: vlog-ops
vlop_id, vlop_title, vlop_description, vlop_tags, vlop_deadline, vlop_quantity, vlop_quantityposted, vlop_vser_id, vlop_usr_id,vlop_loc_name, vlop_loc_lat1, vlop_loc_lon1, vlop_loc_lat2, vlop_loc_lon2, vlop_campaign, vlop_rules, vlop_tips, vlop_status
So in main.php i have written the following Sql lookup
in main.php, I have the following SQL lookups:
$sql = "SELECT * FROM users_gor WHERE usrg_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_gor = $rows[0];
$sql = "SELECT * FROM users_vgr WHERE usrv_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_vgr = $rows[0];
$sql = "SELECT * FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT * FROM vlog-ops WHERE vlop_usr_id ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT usr_name AS vlop_usr_name FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
And then in the page template itself, I have written
<?php echo $vlop['vlop_vser_id'] ?>
<?php echo $vlop['vlop_usr_name'] ?>
The first one works, the second doesn’t. What I want eventually is to display the user name and the organisation name in a table.
Whenever I try a JOIN or a NATURAL JOIN or a LEFT JOIN it breaks and the entire site goes blank.
Any help for a newbie would be appreciated with a million thanks.
When you use JOIN you need to specify how you're joining them.
In the query below I'm assuming you're looking for the fields in bold from your question.
$query='SELECT u.usr_name, g.usrg_orgname, v.vlop_usr_id FROM users u
JOIN vlog-ops v on u.usr_id = v.vlop_usr_id
JOIN users_gor g on u.usr_id = g.usrg_usr_id';
I believe I got the name of the fields right but if not just replace them with the correct ones.
Once you have the data fetched, you just loop through the results:
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
echo 'User name = ' . $row['u.usr_name'];
echo 'Org name = ' . $row['g.usrg_orgname'];
echo 'Job posting user id = ' . $row['v.vlop_usr_id'];
}

Subqueries for php

sorry if this might be a duplicate question but im desperatly needs help for project submission.
I have a database carpark where i have 2 table within which is carpark_availability and history.
From my code, im able to get a field "development" from table carpark_availability.
I would like to ask on how to structure my queries if i want to select * from c where my h.development = c.development.
As shown below is my code:
<?php
session_start();
$con = new mysqli('localhost','root','','carpark_project');
$dev = $_SESSION["development"];
echo "Development: ";
echo $dev;
$sql = "select * from carpark_availability where
carpark_availability.Development IN (select history.development
from history where
history.Development = '$dev' )";
//$sql = "select * from carpark_availability where development = '$dev'";
//$sql = "select * from carpark_availability where (select Development
//from history where Development= '$dev'";
$result = $con->query($sql);
while($row = $result ->fetch_assoc())
{
echo "Development: ";
echo $row["Development"]. "</br>";
echo $row["Area"]."</br>";
echo $row["weekday1"]."</br>";
}
?>
A join is much easier on the eye than a subquery.
SELECT c.*
FROM carpark_availability c
INNER JOIN history
USING (development)
GROUP BY development;
I'm guessing you are getting an error because your query is returning no results so $result is set to boolean false. You have nothing in your code to check for that so you are trying to call fetch_assoc() on it

'Counting' the number of records that match a certain criteria and displaying the numbers (using PHP and MySQL)

I have a MySQL database containing a user's country and whether they are an individual or an organisation. The field names are 'country' and 'type'.
Using PHP, I'd like to 'count' the number of countries, the number of individuals and the number of organisations in the database and then display the numbers in the following example format:
<p>So far, <strong>500</strong> individuals and <strong>210</strong> organisations from <strong>40</strong> countries have registered their support.</p>
I am currently listing the total number of records using the below code if this helps:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$result = mysql_query("SELECT * FROM table_name", $link);
$num_rows = mysql_num_rows($result);
echo " $num_rows\n ";
?>
My PHP / MySQL skills are very limited so I'm really struggling with this one.
Many thanks in advance!
Ben
To get the number of countries:
SELECT COUNT(DISTINCT country) AS NumCountries FROM tableName
To get the number of individuals, or the number of organisations:
SELECT COUNT(*) AS NumIndividuals FROM tableName WHERE type = 'individual'
SELECT COUNT(*) AS NumOrganisations FROM tableName WHERE type = 'organisation'
What you are looking for is a count based on a grouping. Try something like this:
$sql = "SELECT type, count(*) as cnt FROM users GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
This will give you an array like
Array (
'individual' => 500,
'organization' => 210
)
For counting the countries, use the first statement as posted by Hammerite.
EDIT: added a verbose example for counting the countries
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM users";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
This altogether you can then print out:
printf('<p>So far, <strong>%d</strong> individuals and <strong>%d</strong> '.
'organisations from <strong>%d</strong> countries have registered '.
'their support.</p>', $counts['individual'], $counts['organization'],
$number_of_countries);
The answer is to retrieve the answer by using the COUNT(*) function in SQL:
SELECT COUNT(*) AS individual_count FROM user WHERE type = 'individual';
SELECT COUNT(*) AS organization_count FROM user WHERE type = 'organization';
SELECT COUNT(*) AS country_count FROM user GROUP BY country;
The last will group your query set by the country name, and will result in one row for each country. Using COUNT on this result set will give the count of distinct coutries.
You can then fetch this value by using mysql_fetch_assoc on your $result from mysql_query, and the answer will be contained in 'invididual_count', 'organization_count' and 'country_count' for each query.
Thank you for all of your help with this (especially Cassy).
I think it's worthwhile displaying the full code in case anybody else comes across a similar requirement in the future:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$sql = "SELECT type, COUNT(*) as cnt FROM table_name GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM table_name";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
printf('<p><strong>So far, <em class="count">%d</em> individuals and <em class="count">%d</em> organisations from <em class="count">%d</em> countries have registered their support.', $counts['Individual'], $counts['Organisation'], $number_of_countries); ?>
If you're just looking for the number of rows returned try this:
$result = mysql_db_query($db, $query);
$num_rows = mysql_num_rows($result);
Another option would be to execute a separate query with the mysql count function and use the result from that.

Categories