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"];
}
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'm new at programming. This week I have learned the basics of HTML, CSS, PHP and MySQL and I am making a simple turn-based strategy game to practice coding (and have fun while doing it!).
Now, I usually look on DuckDuckGo and YouTube when I am stuck but this time I can't seem to find an answer to my question. Here it is, hope you can help:
I am making the file that will be a cronjob to update the resources my players have. In table 1 (named stockpile) I have columns called village_id, wood, stone and iron. In table 2 (named buildings) I have columns called village_id, woodcutters, quarry and mine. Now here is an example of what I'd like the code to do:
Take 'wood' of village1 and update it like this; wood = wood + (x * woodcutter of village1).
I really hope someone can help me! My project is going fine except for this part I can't seem to wrap my head around...
use a subquery (replace [x] with some value):
UPDATE stockpile s
SET wood = wood + [x] *
(SELECT woodcutters
FROM buildings b
WHERE b.village_id = s.village_id);
You need to SELECT the columns from the table and get the data for the player from those columns, multiply, and update the table. I'm assuming your village_id is a unique index.
$sql = SELECT COUNT(*) FROM table1;
$result = $conn->query($sql);
$sql1 = "SELECT wood FROM table1";
$result1 = $conn->query($sql);
$arr1 = $result1->fetch_assoc();
$sql2 = "SELECT woodcutter FROM table2";
$result2 = $conn->query($sql2);
$arr2 = $result2->fetch_assoc();
for ($i=1;$i<=$result;$i++) {
$newwood = $arr1[$i] + (x * $arr2[$i]);
$sql3 = "UPDATE table1 SET wood=" . $newwood . " WHERE id=" . $i;
$conn->query($sql3);
}
To make it a cron, you need to configure a job with Apache or your other server.
im trying to display a tracking number for a product on opencart.
so once the order has been placed. i then add a tracking number to it. from which i wish the customer to be able to see on the order history.
// get tracking details
$sql = 'SELECT * FROM '.DB_PREFIX.'order_history'.`tracking_number`;
$query = $this->db->query($sql);
$rates = array();
foreach($query->rows as $result){
$rates[] = $result;
}
$this->data['tracking'] = $tracking;
this would also go in order.php
this is what ive written but it dont work, im not expert at php, i dabble in it. hopefully someone can point me in the right direction,
so this code would go into controller/account/order.php
then on the template i assume i can just insert
<?php echo $tracking; ?> to display tracking deteails.
thanks in advance.
Off hand, I can see that this code will result in error, because your quotes/backticks are out of place:
$sql = 'SELECT * FROM '.DB_PREFIX.'order_history'.`tracking_number`;
Should be more along these lines:
$sql = "SELECT `tracking_number` FROM `".DB_PREFIX."order_history`";
And, assuming you're going to want to pull an order-specific tracking #:
$sql = "SELECT `tracking_number`
FROM `".DB_PREFIX."order_history`
WHERE `order_id` = 'MUFFINS'";
Do yourself a favor and use the double quotes when preparing a MySQL query. It's easier to wrap your stuff in single quotes without having to escape.
As for the remainder of the code, these are not rates but tracking numbers. Assumedly, there would be one tracking number to return per order, which you could wrap up into a single line of code like so:
$my_tracking_number = $this->db->query("
SELECT `tracking_number`
FROM `".DB_PREFIX."order_history`
WHERE `order_id` = 'MUFFINS'
")->row['tracking_number'];
if ( !empty($my_tracking_number) {
$this->data['tracking_number'] = $my_tracking_number;
}
However, if you're going to associate more than one tracking number with an order you can either insert a BLOB column in your order_history table and insert/query serialized data, or create a separate table entirely where multiple rows can be associated with a single order ID.
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 ...
}