MySQL while loop query inside other while loop query - php

<?php
include 'config.php';
$conn = mysql_connect("$hostname", "$username", "$password") or die ("Failed to connect to DB.");
mysql_select_db("$dbname",$conn);
$sql="SELECT * FROM opdrachten";
$result=mysql_query($sql,$conn);
while ($row= mysql_fetch_array($result))
{
echo $row['name'];
echo "<br>";
$opdrachtid = $row["id"];
$sql2="SELECT * FROM resultaten WHERE(opdrachtid='".$opdrachtid."')";
$result2=mysql_query($sql2,$conn);
while ($row2= mysql_fetch_array($result2))
{
echo "
<li>
<a href=\"result.php?id=".$row2["id"]."\">
<img src=\"".$row2["img"]." \"width=\"150\" height=\"150\">
<div><span>TEXT HERE</span></div>
</a>
</li>";
}
}
?>
What I want my code to do is (in a loop):
Fetch all rows from the table 'opdrachten' and echo their 'name'.
Grab the 'id' from each of the rows in 'opdrachten' > store in variable $opdrachtid
Fetch rows from table 'resultaten' where 'opdrachtid == $opdrachtid' (which I just stored)
Echo the 'id' and 'img' from the rows fetched from 3.
What I want to see on my page:
The name of the 'opdrachten' (objective) in table 'opdrachten'
with directly underneath
The images (the url's of which are stored in table 'resultaten')that are assigned to these objectives (WHERE opdrachten.id = resultaten.opdrachtid)
I've looked into JOIN since that's the answer to most of the related topic's I've read here, but that doesn't seem to be what I'm looking for since I'm echo'ing in the first while and declare variables that are used for the second query.
Tables used:
'resultaten'
id | opdrachtid | name
'opdrachten'
id | name
Again, resultaten.opdrachtid == opdrachten.id
Thanks in advance, appreciate the help :)

I would certainly suggest using a JOIN here that way you can get all this data in one go. I will add one caveat however - this would take more memory that querying the database in a loop like you are currently doing, so if you have a large number of rows in either table, this might not be a suitable approach.
The query would simply be:
SELECT * FROM opdrachen
INNER JOIN resultaten ON opdrachen.id = resultaten.opdrachenid
You can then set up an array that is keyed on each id very simply like this:
$array = array();
while ($row = mysql_fetch_array($result)) {
$array[$row['id']][] = $row;
}
This give you an easy way to iterate through the results, one id at a time like this:
foreach ($array as $id => $rows_for_id) {
// output stuff for row group
foreach ($rows_for_id as $resultaten_row) {
// output stuff for resultaten rows
}
}
A few other suggestions:
Don't use mysql_* functions as they are deprecated. Learn how to use mysqli or PDO.
Don't use SELECT * queries. Its is lazy and wastes bandwidth, transfer time, and system memory. Only query for the specific fields you are actually interested in. So replace the * in my example with the actual field you need.

SELECT opdrachten.*, resultaten.* FROM opdrachten
INNER JOIN resultaten
ON resultaten.opdrachtid = opdrachten.id;
just use this as the original sql statement and iterate over it.

Related

Fetching one row in database

<?php
$stmt = $conn->prepare('SELECT Distinct(specificcategoryname) FROM `clientstable` c,specificcategories s where c.PhoneNumber=:phNo and c.SpecificCategoryId=s.SpecificCategoryId');
$stmt->execute(['phNo'=>$phNo]);
while($row = $stmt->fetch()) {
echo "<tr>";
echo "<td>".$row['specificcategoryname']."</td>";
echo "</tr>";
}
?>
I have code like this need to fetch only one specific value from the database. how can i get the preferred value?
Your, where clause is matching with more than one records that's why more than one records are fetching. if you want to select specific single record then there should be change in sql query. I can't more help because, i need to see the complete schemas of both tables ( clientstable and categorytable) that you are using. Thank you

PHP while loop that prints sql content, with another query inside to another sql table?

I hope my title says something about what I am trying to do, I'll try to describe it a bit better:
I have a database with two tables, one named "movies" and another one named "directors".
Its a small movie database where we are supposed to be able to display all the movies, their title, year and producer.
In the table "directors" I have a field "id" and in my "movies" table i have a field named "producer" with the matching id. I want the while loop to loop thru all the movies in the "movies" table (working fine) and if i choose to print the "id" from "movies" its correct.
But now i want the loop to display the "title" and "year" from the "movies" table, and go to the "directors" table and get the name for the matching "id".
I'm new to both PHP and mysql queries and my code does this correctly for the first movie, but the rest have their "producer" field empty as for now.
(Right now I'm just trying to display the surname to see that it works).
FYI this is for a school project.
Code:
<?php
$sql = "SELECT * FROM movies ORDER BY title ASC";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$id = $row['id'];
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$title=mysql_result($result,$i,"title");
$year=mysql_result($result,$i,"year");
$producer=mysql_result($result,$i,"producer");
$id=mysql_result($result,$i,"id");
$sqldir = "SELECT * FROM directors WHERE id='$producer'";
$result1 = mysql_query($sqldir);
$row1 = mysql_fetch_assoc($result1);
$iddir = $row['id'];
$producertext = mysql_result($result1,$i,"surname");
?>
<b>Title:</b> <?php echo $title ?>
<br/><b>Year:</b> <?php echo $year ?>
<br/><b>Director:</b> <?php echo $producertext ?>
<br/>
</form> <HR>
<?php
$i++;
}
?>
Assuming that every movie has a single director then you can just create a joined query
SELECT movies.title as title, movies.year as `year` producer.surname as surname
FROM movies, producer where movies.producter = producer.id ORDER BY title ASC
You can then just walk the result set and the surname will be in the result arrays.
Here should be a complete solution assuming the query works as expected
<?php
$sql = "SELECT movies.title as title, movies.year as `year` producer.surname as surname FROM movies, producer where movies.producter = producer.id ORDER BY title ASC";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)): ?>
<b>Title:</b> <?php echo $row['title'] ?>
<br/><b>Year:</b> <?php echo $row['year'] ?>
<br/><b>Director:</b> <?php echo $row['surname]; ?>
<?php
endwhile;
?>
You are using wrong function
$num=mysql_numrows($result);
you should use
$num=mysql_num_rows($result);
You're accessing the producer information as:
$producertext = mysql_result($result1,$i,"surname");
However, $i is the index from the main SQL loop; so on the second run through, you'll be looking for the surname from the second line of your producer result set, which won't necessarily be there. So only the first producer is showing up.
Some other things you might want to look at - you can use PDO or mysqli to access data - they're more secure that mysql, which is in the process of being deprecated. You're also using mysql_fetch_assoc at the moment, but you don't seem to be using the resulting array for anything. It's a lot more common to go through a result set with something like:
while ($row = myssql_fetch_assoc($result)) {
....
}
Which loads the next row into an associative array for you to use, and stops when you run out of rows.
Also, have you considered what your code should do if there's more than one producer for a film? You might want to add a loop for that query, too.

Echo a selected id from MySQL table

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks
If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}
From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.
mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

Subquery in PHP

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 ...
}

How to I pull information from MySQL with PHP?

I am asking if it is not only possible to pull data from a MySQL table, but also display each row in either a table or a DIV, preferably a DIV. How would I do so?
Table:
ID |BodyText |Title |
1 |Hello World1 |Title1 |
2 |Hello World2 |Title2 |
etc..
I'd like to put each row into a DIV that has a title and also bodytext, but I want php to generate these tables and put the info into each DIV.
Possible to do?
We will use this table as an example data set:
Database Name: friends
-----------------------------
| firstname || lastname |
----------------------------
|Chris || Geizz |
|Steve || Michalson |
|Ken || Bohlin |
|Doug || Renard |
-----------------------------
First you must connect to your database as so:
http://www.w3schools.com/PHP/php_mysql_connect.asp
You would run a MYSQL query to get the data from the MySQL Database:
$query = mysql_query("SELECT * FROM friends");
Then you would use the following to put them into a table:
echo "<table><tr><td>First Name</td><td>Last Name</td></tr>";
while($row = mysql_fetch_array($query))
{
echo "<tr><td>";
echo $row['firstname'];
echo "</td><td>";
echo $row['lastname'];
echo "</td></tr>";
}
echo "</table>";
What this basically does is pulls the information that is returned with my mysql_query and puts it into an array that you can call with the $row variable we set. We do this in the while loop so that it repeats for all records in your database.
The code before the while loop and after the while loop are there so that way it is all in one table and we are just making rows instead of separate tables for each row in your database.
This will accomplish what you want. When you are doing the while loop you can use the variables ($row['firstname'] and $row['lastname']) as you wish. You could place them in seperate DIV's if you wish as well.
Hope this helps you! If you have any questions leave a comment and I will respond.
Basically you can do whatever you want, once you have the rowset. The general structure of such code (if layers not devided / MVC) looks like this:
connect to db
write query
retrieve results
loop for each row in resultset
{
echo html and column content as you wish
}
so for example you could use
foreach ($rowset as $row)
{
echo '<div>'.$row['column1'].' is a friend of '.$row['column2'].'</div>';
}
Here's the manual pages for how to access/query MySQL databases:
MySQL: http://www.php.net/manual/en/book.mysql.php
MySQLi: http://www.php.net/manual/en/book.mysqli.php
Using the functions there you can easily query and display the data as you see fit. If you are wanting to access column info (field names) you either need to use the access the information_schema tables or use queries like describe table.
Update: based on the comments, the question relates more to Tharkun's answer than this.
<?php
$result = mysql_query("SELECT * from table");
if($result && mysql_num_rows($result))
{
$numrows = mysql_num_rows($result);
$rowcount = 1;
while($row = mysql_fetch_assoc($result))
{
print "<div><b>$rowcount</b>";
foreach($row as $var => $val)
{
print"|$var: $val|";
}
print "</div>";
++$rowcount;
}
}
?>

Categories