What is an SQL query for counting records that are existing more than once in a database? - php

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("students");
$id = $_POST['id'];
$grade = $_POST['grade'];
$query = "INSERT INTO `st_table` (`St_id`,`Grade`) VALUES ('$id','$grade')";
$result = mysql_query($query);
$query = "SELECT * from `st_table`";
$result = mysql_query($query);
echo "<table>";
echo "<th>St_id</th><th>Grade</th>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['St_id'] . "</td><td>" . $row['Grade'] . "</td></tr>";
}
This code adds values into a table both ID and Grade. I want another query that will be able to count how many As, Bs, Cs, etc. and OUTPUT it on an html table.

Here, Your query is ok just group by Grade not Grades
"SELECT `Grade`, COUNT(*) AS count FROM `st_table` GROUP BY `Grade`";
Here is sqlfiddle
After edit
The query i am mentioning should work for you, you can check fiddle for that as for as you modified code is concerned you have to change your table a bit since you are going to include St_id as well so make it 3 column and correspondingly change query too.

Related

How to count amount of students per university

I have a SQL database of university students, with the following details:
Table_name: register
Column_names: position, tertinst
The data in the database will look something like this:
Coach..........UCT
Athlete........Tukkies
Official.......University of JHB
Athlete........Tukkies
Athlete........Tshwane Tech
Manager........UCT
I need to count the amount of students who are athletes(position), per university(tertinst) and the output has to be something like this:
UCT.....................735
University of Jhb.......668
Tukkies.................886
this is my attempt:
$positionx = 'Athletes';
include_once 'core/includes/db_connect.php';
$sql = "SELECT tertinst, COUNT(position) FROM register WHERE position = '$positionx' GROUP BY tertinst ";
$result = $conn->query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['COUNT(tertinst)'] . '......' . $row['COUNT(position)'];
}
$conn->close();
I get no result when the code is executed and I have searched for a different solution for hours, without success.
I made a few mistakes, and corrected the syntax in the sql count, as well as the echo. Here is the solution to my problem:
<?php
include_once 'core/includes/db_connect.php';
$sql = "SELECT tertinst, COUNT(*) total FROM register WHERE position = 'Athletes' GROUP BY tertinst ";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$tertinst = $row["tertinst"];
echo $tertinst . '......' . $row['total'] . '<br>';
}
$conn->close();

Query does not work when i fetch data and insert it into a table

I am trying to insert to another table the results of a select statement from another table. The select statement works but the insert statement does not work. Please help me.
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
}
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
header("Location:homeclient.php");
?>
You asked for how to do these two as one query.
This is how:
$query = mysql_query("INSERT INTO `client` ( `client_csub_code`, `client_csub_name`, `client_csub_day`, `client_csub_time` ) SELECT `sub_code`, `sub_name`, `sub_day`, `sub_time` FROM `subject` WHERE `code` = '$enrol'");
// I would also add error checking
if ( mysql_errno() )
echo mysql_error();
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
}
header("Location:homeclient.php");
?>
Try changing to this. Currently your query is outside of your while, it will only run once and the values of $csubject etc are always going to be the last values of your fetched results.

PHP script to search mysql database doesn't return result

Following the code I wrote. This doesn't return any values, even though the table has the keywords.
<?php
$conn = mysql_connect("localhost", "root", "qwerty");
mysql_select_db("mis", $conn);
$coursename=$_POST['coursename'];
$sql = "SELECT *
FROM course
WHERE coursename='$coursename'".
"ORDER BY coursename";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
echo $row['coursename'];
};
?>
The problem is case-sensitivity. MySQL identifiers are not case sensitive unless you enclose them in backticks. However, PHP array indexes are.
Therefore if you have a column named CourseName, the following query will work:
SELECT *
FROM course
WHERE cOuRSEnaME = 'foo'
ORDER BY courSEnAmE
But, referencing it in PHP as $row['coursename'], $row['cOURsENamE'] or any other differing combination will not work, as these all refer to different keys. You must use $row['CourseName'].
See also: PHP array, Are array indexes case sensitive?
Try to add error_reporting(E_ALL); immediately after your <?php and see if you get any error messages from your browser.
You should be able to track down the root cause of your problem.
Good luck with your coursework (i guess ;).
$sql = "SELECT *
FROM course
WHERE coursename='$coursename'".
"ORDER BY coursename";
Your code is good but it is much better to use concatenate the string and the variable so it is easily interpreted and also I wanna point out that there is no space before your ORDER BY statement that can cause an error, so make sure there are spaces between them coursename = '" . $coursename . "' ORDER BY. See the full query below
$sql = "SELECT *
FROM course
WHERE
coursename = '" . $coursename . "' ORDER BY coursename";
$sql = "SELECT *
FROM course
WHERE coursename='" . $coursename . "'
ORDER BY coursename";
$result = mysql_query($sql, $conn);
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo $row['coursename'];
}
} else {
echo "given coursename does not exist";
}
?>

How to ignore duplicate rows when echoing mysql query result

I trying to make tag cloud system and i enter the tags in one table with "name" and "product_id".
I make that may have multiple same tags everyone for different product.
My problem is that when echo the tags from the table it show me all tags,this is good,but the repeated tags are in that count. I need to echo repeated tags only once, but i don't know how to make that.
Here is and my code that showed and repeated tags.
$id = $_GET['catid'];
$sql = "SELECT * FROM tags_group";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
//echo $row['name'];
$id = $row['id'];
$sql1 = "SELECT * FROM tags WHERE tag_group='$id'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_array($result1)) {
$name = $row1['tag_name'];
$sql2 = "SELECT * FROM tags WHERE tag_name='$name'";
$resut2 = mysql_query($sql2);
$rows = mysql_num_rows($resut2);
echo $row1['tag_name'] . '(' . $rows . ')' . '<br>';
// echo $row1['tag_name'].$rows.'<br>';
}
echo '<br>';
}
You have to use the DISTINCT keyword do avoid duplicates:
SELECT DISTINCT * FROM tags_group
As I mentioned in the comments above, you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.
UPDATE
It also looks like you're using nested queries, rather than joining your tables and retrieving the results. Try this instead:
$id = $_GET['catid'];
$sql = "SELECT tags.tag_name, count(*) AS name_count FROM tags
INNER JOIN tags_group
ON tags.tag_group = tags_group.id
GROUP BY tag_name";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$name = $row['tag_name'];
$rows = $row['name_count'];
echo $name . '(' . $rows . ')' . '<br>';
// echo $row['tag_name'].$rows.'<br>';
}
echo '<br>';
Here I don't use DISTINCT but GROUP BY allows you to aggregate the count for each distinct row (based on the GROUP BY column).
Take a look at this diagram to better understand how joins work.

mySQL database: printing specific row or rows from a db table

please assist. i have a database with a couple of tables and rows and i want the php to print specific rows as and when i want it to. at the moment it renders all the content of the spesific table on my webpage. in future, i would like it to display the contents of a specific table if a cirtain user is logged in so im going to do that when i understand if statements and get over this hurdle 1st. my code is as follows:
<?php
include 'connect-mysql.php';
echo "<br/>";
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}
?>
To fetch specific rows from a table you have to include a WHERE clause in your SQL statement.
For example:
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer WHERE customer_id = 2";
Match the WHERE xxxxx clause to any column in your table
You need to specifiy yor criteria as a where clause in the SQL
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer where RAMSCODE = %1";
$result = mysql_query($query,mysql_real_escape_string($yourcode)) or die (mysql_error());
Also you really need to Read the Manuals!
As far as i've get what you want is to display only that row from customers table, which customer is logged in. you can use some thing like this:
while($row = mysql_fetch_array($result))
{
if($row['CUSTOMER_NAME'] == " //Customer Logged In (customer name from session)"){
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}else{
//do nothing or continue with printing all
}
}
Hope this helps.

Categories