I've developed a database, where i have three sets of columns:
- Username
- Feeling
- Remark
The entry's for feelings are all the same, because they're being selected from a dropdown menu. I'm looking for a way to count the amount of same results and then echo it on a site with PHP, but I can't get any further than this:
<?php
$con=mysqli_connect("localhost","username","password", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT COUNT(*) FROM thefeels WHERE feeling = 'Happy'";
$result = mysqli_query($con, $query);
var_dump($result)
?>
In this code I want to count the amount of times happy occurs in a column, but even that is not working. How can I count the amount of times the same results is in a column?
So if Happy is there four times and Sad two times it should display:
Happy: 4
Sad: 2
This is a basic Counting Rows task. You will find some examples in the official documentation.
In your case it would be:
$query = "SELECT feeling, COUNT(*) as count FROM thefeels GROUP BY feeling";
$result = mysqli_query($con, $query);
Now you can use the "old school" way (which you will find in many totorials):
while ($row = mysqli_fetch_assoc($result)) {
echo "{$row['feeling']}: {$row['count']}<br>";
}
or move forward and separate data fetching from data processing and data output with:
$feelingCounts = $con->fetch_all(MYSQLI_ASSOC);
And do what ever you need with the fetched data. For example:
var_dump($feelingCounts);
Use conditional aggregation:
SELECT COUNT(CASE WHEN feeling = 'Happy' THEN 1 END) as Happy,
COUNT(CASE WHEN feeling = 'Sad' THEN 1 END) as Sad
FROM thefeels
Related
I have 2 tables, 1 with companies(Costcenters) and one with clients (employees of those companies)
i need to make a form to edit or delete malformed ( like john smit and j. Smit) from those companies employees grouped by company (Costcenter), when i make a list with all those companies i get a lot of companies that has no clients. So I made a array of the companies (Costcenters) and check first if they have employees, this with the goal to remove the Costcenters without employees from the array ($bedrijven).
The form is no problem, but i cant find a way to get those companies removed from the bedrijven array.
require_once('conn.php');
$query = "SELECT bedrijfID, Houder, Costcenter, Actief FROM bedrijven
WHERE Actief = 'actief' ORDER BY Costcenter";
$results = mysqli_query($conn, $query);
if (!$results) printf("Query failed: %s\n", $conn->error);
$bedrijven = [];
while($row = mysqli_fetch_assoc($results)) {
$bedrijven[] = $row['Costcenter'];
}
foreach ($bedrijven as $key => $item) {
$query1 = "SELECT * from customer where Costcenter = '$item' ORDER by
Client";
$customerresult = mysqli_query($conn, $query1) or
die(mysqli_error($conn));
if (!$customerresult) printf("Query failed: %s\n", $conn->error);
if($customerresult->num_rows === 0) {
unset($bedrijven[$key]);
}
}
I am not familiar with PDO or funtions so tried it this way that does not work as i expected, the unset is not working.
the code is editted as it is working now, i hope it might help others as well. If any has a better solution please post.
If I understand what you are going for, this is better done as a single Query. A JOIN can be used first to bind your tables, and then additional WHERE operators can be used if needed to refine your search. I'm not 100% sure if I'm reading right that this is is exactly how you wanted to join the data, but if you play with different JOIN operators you'll get it.
$query = "SELECT Costcenter.bedrijfID, Costcenter.Houder, Costcenter.Costcenter, Costcenter.Actief, customer.* FROM Costcenter
LEFT JOIN customer ON customer.Costcenter = Costcenter.Costcenter
WHERE Actief = 'Costcenter.actief' AND Costcenter.Costcenter != "" ORDER BY Costcenter.Costcenter";
The biggest reason for doing it this way this that a single SQL call processes WAY faster than trying to parse your data from multiple calls in PHP.
thanks to the requestion of The fouth bird i discovered i have been wasting a lot of time on a simple solution. i should not have done :
unset($bedrijven['Costcenter']);
but
unset($bedrijven[$key]);
you must unset the key in the array not the value....
I am using php and mysql to create a page that displays all of the jobs we have in the database. The data is shown is a table and when a row is clicked a modal window triggers with the information of the clicked job inside. At the top of the page I want a simple counter that shows amount of paid jobs, invoiced jobs etc etc. I am using the code below but having no luck...
<?php
$con = mysql_connect("localhost","databaseusername","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("databasename", $con);
$result = mysql_query("select count(1) FROM jobslist");
$row = mysql_fetch_array($result);
$total = $row[0];
mysql_close($con);
?>
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0. No matter what I try I can't seem to get it to count the amount of 'paid' items in the database or 'invoiced' etc etc.
Once the count function is complete currently I am echoing out the outcome as below:
<?php echo "" . $total;?>
I am sure I am overlooking something simple, but any help is appreciated.
EDIT: TABLE STRUCTURE INCLUDED
http://i.stack.imgur.com/hcMJV.png
Assuming a column called paid you could restructure the query similar to the following. If you needed to sum the amounts involved that requires additional tweaking.
$result = mysql_query("select
( select count(*) from `jobslist` where `paid`=1 ) as 'paid',
( select count(*) from `jobslist` where `paid`=0 ) as 'unpaid'
from jobslist");
$rows = mysql_num_rows( $result );
while( $rs=mysql_fetch_object( $result ) ){
$paid=$rs->paid;
$unpaid=$rs->unpaid;
echo 'Total: '.$rows.'Paid: '. $paid.' Unpaid: '.$unpaid;
}
When I do this I usually name the COUNT result. Try this out:
$result = mysql_query("SELECT COUNT(*) AS total_rows FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['total_rows'];
If you do not want to name the COUNT result, then give the following a go:
$result = mysql_query("SELECT COUNT(*) FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['COUNT(*)'];
select count(1) FROM jobslist
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0.
No, this is just counting rows in your table and not filtering. If you want to count something with a specific filter you have to add that filter condition:
SELECT COUNT(*) AS `MyCount`
FROM `joblist`
WHERE `MyColumn` = 1; -- assuming MyColumn contains the INT you're looking for
You should stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
First you should change deprecated mysql_... to mysqli_... (look here how to). But it's not the reason you fail.
Unlike you seem to suppose, COUNT(1) will not look for an INT column having value 1.
Instead you must use COUNT(*) or COUNT(a_column_name) (same result), with adding a WHERE clause stating which condition is involved.
Here you seem wanting to count records where a given column (say the_column) has value 1. So you should:
SELECT COUNT(*)
FROM jobslist
WHERE the_column = 1
Last point: you don't need echo "" . in <?php echo "" . $total;?>.
Merely write <?php echo $total;?>.
Basically, I'm coding a site that has many different categories and I want to display the amount of rows specific to that ID.
So for example, I have as the query:
$query= "SELECT job_sec FROM jobs WHERE job_sec = ?";
mysqli_num_rows($query);
I need to know how I can count the rows of an ID then echo the rows counted.
I'd like the results to display:
Web Design: 2,001 jobs
Logo Design: 5,120 Jobs
The job_sec column just uses a numerical value, would it be easier to have a text value then count the rows relating to the text value and echo them?
I have a feeling I need to use an array however I need the most efficient method.
Any help would be much appreciated!
Assuming job_sec is the category and I think you are looking for "group by":
$sql= "SELECT job_sec, count(*) AS c FROM jobs GROUP BY job_sec";
$r = mysqli_query($sql);
while ($row = mysqli_fetch_assoc($r)) {
echo $row['job_sec'] . ': ' . $row['c'] . ' Jobs ';
}
(didn't test and not sure if the mysqli syntax is correct)
I have an application to add friends. I need to have my script to check, if the users' already friends. I thought I could do this by a COUNT. I did like this:
$username = $_GET[user];
$ven_til_id = $_SESSION['userID'];
$num = 1;
if(isset($_GET['add_friend'])){
$check=("SELECT username,ven_til_id, COUNT(*) AS num FROM friends WHERE username=$username AND ven_til_id=$ven_til_id GROUP BY username,ven_til_id")or die(mysql_error());
$result=mysql_query($check);
if(!$result){
echo "Cant run query.";
} else {
$num = mysql_num_rows($result);
}
if($num>0){
header("Location: /profil/$username?add_error");
} else {
$sql=mysql_query("INSERT INTO friends (username,ven_til_id)VALUES('$username', '$ven_til_id')")or die(mysql_error());
header("Location: /profil/$username");
}
}
?>
But when I'm adding one friend it's fine. It adds it and everything is fine. But then when I try to add another, it says we're already friends. I guess it's because it's counting how many times my ID (ven_til_id) is listed in the tables.
You're missing a comma:
SELECT
username,ven_til_id COUNT(*) AS num FROM ...
should be
SELECT
username,ven_til_id, COUNT(*) AS num FROM ...
Also, your reference to the count field is incorrect - it should be the third column or $row[2]
You may want to make your code more robust by referring to fields by name eg $row['num']
One final thing to confirm is that the value being retrieved with a count is being treated as an integer not a string. I don't think it's the problem here but you may want to explicitly cast it to avoid possible issues later eg...
$num = (int) $row[2];
Option 1
Just select the appropriate rows and see how many records you get back...
SELECT username,
ven_til_id
FROM friends
WHERE username=$username
AND ven_til_id=$ven_til_id
Then just count the number of records returned using PHP - eg mysql_num_rows() (I think that's the correct function name)
Clarification:
Change
$row = mysql_fetch_row($result);
$num = $row[2];
to
$num = mysql_num_rows($result);
Option 2
Get MySQL to do the counting for you - in qhich case you need to tell it to group multiple record together...
SELECT username,
ven_til_id,
COUNT(*) as Num
FROM friends
WHERE username=$username
AND ven_til_id=$ven_til_id
GROUP BY username,
ven_til_id
Then just read the 3rd value of the first row (num) and you'll have a count
NB: The second method may be overkill if you're only ever expecting a 1 or a 0
I'm doing this project for university, which is basically a movie database and for a couple of queries I need to know how many rows were selected. For now, there's 2 situations where I need this:
Display a single movie information. I want the count of selected rows to know if the database contains the selected movie by the user. Or is there a better solution for this?
That selected movie has genres, I need to know how many so that I can construct a string with the genres separated by | without adding one to the end of the string.
With MySQL this is easy, I just query the database and use mysql_num_rows() but oci_num_rows() doesn't work quite the same for the SELECT statement.
The only solution I found with OCI/PHP is this:
if(is_numeric($mid) && $mid > 0) {
$stid = oci_parse($db,
'SELECT COUNT(*) AS NUM_ROWS
FROM movies
WHERE mid = '.$mid
);
oci_define_by_name($stid, 'NUM_ROWS', $num_rows);
oci_execute($stid);
oci_fetch($stid);
if($num_rows > 0) {
$stid = oci_parse($db,
'SELECT title, year, synopsis, poster_url
FROM movies
WHERE mid = '.$mid
);
oci_execute($stid);
$info = oci_fetch_assoc($stid);
$stid = oci_parse($db,
'SELECT COUNT(*) AS NUM_ROWS
FROM genres g, movies_genres mg
WHERE mg.mid = '.$mid.' AND g.gid = mg.gid'
);
oci_define_by_name($stid, 'NUM_ROWS', $num_rows);
oci_execute($stid);
oci_fetch($stid);
$stid = oci_parse($db,
'SELECT g.name AS genre
FROM genres g, movies_genres mg
WHERE mg.mid = '.$mid.' AND g.gid = mg.gid');
oci_execute($stid);
$genres_list = null;
while($row = oci_fetch_assoc($stid)) {
$genres_list .= $row['GENRE'];
if($num_rows > 1) {
$genres_list .= ' | ';
$num_rows--;
}
}
$Template->assignReferences(array(
'Index:LinkURI' => $link_uri,
'Movie:Title' => $info['TITLE'],
'Movie:Year' => $info['YEAR'],
'Movie:GenresList' => $genres_list,
'Movie:Synopsis' => $info['SYNOPSIS'],
'Movie:PosterURL' => $info['POSTER_URL'] // FIX: Handle empty poster link
));
$Template->renderTemplate('movieinfo');
} else {
// TODO: How to handle this error?
}
} else {
// TODO: How to handle this error?
}
But I don't like it. I always need to make 2 queries to count the rows and then select the actual data and there's too many lines of code just to count the rows.
This code doesn't show it (haven't done it yet cause I'm looking for a better solution) but I'll also need to do the same for the movie directors/writers.
Is there any better and simpler solution to accomplish this or this is the only way?
I could add separators in the fetch loop until it finishes and then use PHP functions to trim the last separator from the string, but for this project I'm forced to use SEQUENCES, VIEWS, FUNCTIONS, PROCEDURES and TRIGGERS. Do any of these help solving my problem?
I know what SEQUENCES are, I'm using them already but I don't see how can they help.
For VIEWS, they probably wouldn't simplify the code that much (it's basically a stored query right?). For FUNCTIONS, PROCEDURES and TRIGGERS, as far as I understand them, I can't see how can they be of any help either.
Solutions?
Why do the initial count at all? Just issue your select for the movie title. If it's not found, do your error processing. If it is, continue on! If you really need the count, use an analytic to add the count to your query:
'SELECT title, year, synopsis, poster_url
, COUNT(*) OVER (PARTITION BY mid) mcount
FROM movies
WHERE mid = '.$mid
The same goes for your genre selection.
EDIT:
Oracle documentation on Analytic Functions link. I found that analytics are a bit difficult to get from the Oracle docs. Analytic functions by Example by Shouvik Basu provides some simple guidance as to how to use them and helped me quite a bit.
You can try this
$conn = oci_pconnect('user', 'password', 'connectionstring');
$resource = oci_parse($conn, $sql);
oci_execute($resource, OCI_DEFAULT);
$results=array();
$numrows = oci_fetch_all($resource, $results, null, null, OCI_FETCHSTATEMENT_BY_ROW);
Cheers
you can use the ocirowcount it should behave just like mysql_num_rows when making a select
oci_num_rows() Will give you the total row count if executed AFTER oci_fetch_array()