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....
Related
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
I'm trying to get my head around how I would do a particular MYSQL query but can't figure it out.
I have a table called developers and a table called plots. All of the plots have a developer id which links back to a developer name in the developers table.
I'm trying to output the developer name and then all the plots numbers under that developer. Once it's done that, I want it to do the same again with any more developers that may exist.
I've tried using joins however it will simply print:
developer name, plot number,
developer name, plot number,
developer name, plot number,
I only need the developer name to display once. However I need to print all the plot numbers.
I thought about having some kind of IF statement in the while loop where if the developer name is the same as it was previously in the last loop then it wont print. However I can't seem to figure out how that would work.
Thank you all for your help.
you can do in two steps
1. to get developer name and id.
2. get all plots of that id
$sql1 = "SELECT developer_id, developer_name FROM developers ";
$res = mysqli_query($con, $sql1);
while($row = mysqli_fetch_array($res))
{
$developer_id = $row['developer_id'];
$developer_name = $row['developer_name'];
echo $developer_name;
$sql2 = "SELECT * FROM plots WHERE developer_id='$developer_id' ";
$res2 = mysqli_query($con, $sql2);
while($row2 = mysqli_fetch_array($res2))
{
echo $row2['plot_id'];
}
}
This won't give you an output as exactly u need. But maybe this would do the job.
select developer_name, group_concat(plot_number SEPARATOR ',') from developer inner join plot on plot.developer_id = developer.developer_id group by developer_name
You can then explode out(PHP Explode with comma as the delimiter) the plot_number column from the result set to show all the plot numbers corresponding to a developer.
Use a Left Join..
Select * From developers Left Join plots on developers.developerid=plots.developerid
So it'll select everything from table developers and for each developer, it should select the plots.
Use an if condition to check if the last result of the developer id is equal to the current. If it is no, print the id.
Edit:
Here's how the PHP program should run..
$strSQL = "Select * From developers Left Join plots on developers.developerid=plots.developerid";
$Result = mysql_query($strSQL);
$DevID = "";
while ($Fields = mysql_fetch_array($Result))
{
if ($Fields["developerid"] != $DevID)
{
echo $Fields["developerid"];
$DevID = $Fields["developerid"];
}
echo $Fields["plot_column"];
}
// make empty array
$sqlArray=array();
$jsonArray=array();
// START NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// first 20 vistors
$query = "SELECT user_id FROM vistors LIMIT 20";
$result = mysql_query ($query) or die ($query);
// make vistors user query array
while ($vstr_line = mysql_fetch_array($result)){
array_push($sqlArray, $vstr_line['user_id']);
}
// implode vistors user array
$sqlArray_impl = implode("', '", $sqlArray);
// END NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN ('$sqlArray_impl')";
$qry_result = mysql_query($query) or die($query);
while ($usr_line = mysql_fetch_array($qry_result)){
array_push($jsonArray, $usr_line['id'].' - '.$usr_line['username'].' - '.$usr_line['picture']);
}
print_r($sqlArray);
echo '<br><br>';
print_r($jsonArray);
see this my functions..
i need a replacement for fast working alternatives..
function within the range specified above, to me, running faster than the alternative.
the query will return back array ?
thx for all helpers !
Can you use a JOIN or SUB SELECT to reduce the query count from 2 to 1? Might not give much of a boost but worth a shot and a cleaner implementation.
Where is the bottleneck? Most likely the db and not the php code.
Are the tables/columns properly indexed? Run EXPLAIN on both queries.
Easiest would be to include first query as subquery eliminating one turn to the DB and a lot of code:
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN (SELECT user_id FROM vistors LIMIT 20)";
$qry_result = mysql_query($query) or die($query);
Unless there is more reason to have the first one seperate, but that is not visible in your code example.
If you use PDO (recommended anyway...), you can return the result array all at once using fetchAll().
For your second query, you can use string concatenation in MySQL to directly return the result you want.
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()
Let's put an easy example with two tables:
USERS (Id, Name, City)
PLAYERS (Id_Player, Number, Team)
And I have to do a query with a subselect in a loop, where the subselect is always the same, so I would like to divide it into two queries and put the subselect outside the loop.
I explain. What works but it is not optimize:
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN (SELECT Id FROM USERS WHERE City='London')");
}
What I would like to do but it doesn't work:
$res1=mysql_query("SELECT Id from USERS where City='London'");
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN **$res1**");
}
Thanks!
Something like this should work.
<?
$sql = "SELECT Team from PLAYERS
JOIN USERS on (Id_player=Id)
WHERE Number BETWEEN $minID AND $maxID
AND City='London'
GROUP BY Team";
$results=mysql_query($sql) or die(mysql_error());
// $results contain all the teams from London
// Use like normal..
echo "<ul>\n";
while($team = mysql_fetch_array($results)){
echo "\t<li>{$team['Team']}</li>\n";
}
echo "</ul>";
Placing SQL quires in loops can be very slow and take up a lot of resources, have a look at using JOIN in you SQL. It's not that difficult and once you've got the hang of it you can write some really fast powerful SQL.
Here is a good tutorial worth having a look at about the different types of JOINs:
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
SELECT PLAYERS.*, USERS.City FROM PLAYERS, USERS WHERE USERS.City='London' AND PLAYERS.Number = $i
Not the best way to do it; maybe a LEFT JOIN, but it should work. Might have the syntax wrong though.
James
EDIT
WARNING: This is not the most ideal solution. Please give me a more specific query and I can sort out a join query for you.
Taking your comment into account, let's take a look at another example. This will use PHP to make a list we can use with the MySQL IN keyword.
First, make your query:
$res1 = mysql_query("SELECT Id from USERS where City='London'");
Then, loop through your query and put each Id field one after another in a comma seperated list:
$player_ids = "";
while($row = mysql_fetch_array($res1))
{
$player_ids .= $row['Id'] . ",";
}
$player_ids = rtrim($player_ids, ",");
You should now have a list of IDs like this:
12, 14, 6, 4, 3, 15, ...
Now to put it into your second query:
for($i = 0; $i<something; $i++)
{
$res2 = mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN $player_ids");
}
The example given here can be improved for it's specific purpose, however I'm trying to keep it as open as possible.
If you want to make a list of strings, not IDs or other numbers, modify the first while loop, replacing the line inside it with
$player_ids .= "'" . $row['Id'] . "',";
If you could give me your actual query you use, I can come up with something better; as I said above, this is a more generic way of doing things, not necessarily the best.
Running query in a loop is not a great idea. Much better would be to get whole table, and then iterate through table in loop.
So query would be something like that:
"SELECT Team from PLAYERS WHERE Number BETWEEN($id, $something)
AND Id_Player IN (SELECT Id FROM USERS WHERE City='London')"
$res1=mysql_query("SELECT Id from USERS where City='London'");
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN **$res1**");
}
Would work, but mysql_query() returns a RESULT HANDLE. It does not return the id value. Any select query, no matter how many, or few, rows it returns, returns a result statement, not a value. You first have to fetch the row using one of the mysql_fetch...() calls, which returns that row, from which you can then extract the id value. so...
$stmt = mysql_query("select ID ...");
if ($stmt === FALSE) {
die(msyql_error());
}
if ($stmt->num_rows > 0) {
$ids = array();
while($row = mysql_fetch_assoc($stmt)) {
$ids[] = $row['id']
}
$ids = implode(',', $ids)
$stmt = mysql_query("select TEAM from ... where Id_player IN ($ids)");
.... more fetching/processing here ...
}