Mysql select multiple queries inside eachother - php

I am having some trouble with selecting data from my database using data from a previous select. What I want to do is. First I let mysql select all vechiles from my database from the table vechiles. I echo them and inside the while loop I try to select the picture for the vechile from a diffrent table by select the picture with the vechile_id:
Now my first question is. Is this the right way to do it? I assume there must be a more neat way but I cant find how.
<?php
$sql = "SELECT id, brand FROM vechiles";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sql1 = "SELECT * FROM fotos WHERE vechiles_id =". $row['id'];
$result1 = $conn->query($sql1);
echo '<li><p class="title">'. $row['brand'] .'</p>
<p class="type">type: 2387</p>
<p class="ez">ez: 1987</p>';
if ($result1->num_rows > 0) {
// output data of each row
while($row1 = $result1->fetch_assoc()) {
echo '<img src="admin/'. $row1['url'] .'" atl="tractor 1"/>';
}}else{
echo "there are no pictures";
}
echo '<div class="info">
<p class="prijs">Prijs: 1800,- EX BTW</p>
<p class="msg"> Prijzen onder voorgehoud</p>
</div>
<a class="button" href="#">Meer info</a></li>';
}
} else {
echo "0 results";
}
$conn->close();
?>
Noe the above example works fine but I want to only select the first picture instead of all uploaded pictures.
So to this code:
$sql1 = "SELECT * FROM fotos WHERE voertuig_id =". $row['id'];
I added
$sql1 = "SELECT TOP 1 * FROM fotos WHERE voertuig_id =". $row['id'];
And I also tried
$sql1 = "SELECT * FROM fotos WHERE voertuig_id =". $row['id'] . "LIMIT 1";
But when I do that it suddenly says there are no pictures. What am I doing wrong!
appreciate all the help!

You don't need to loop and execute another query for each vehicle, you can do it with a simple join.
select *
from vehicles v
left join fotos f
on f.voertuig_id = v.id;
If there is no matching photo for that vehicle, it will have a null value in your returned array.
This will change your php to something like this:
$last_vehicle = null;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if($row['brand'] != $last_vehicle) {
if($last_vehicle != null) {
echo '<div class="info">
<p class="prijs">Prijs: 1800,- EX BTW</p>
<p class="msg"> Prijzen onder voorgehoud</p>
</div>
<a class="button" href="#">Meer info</a></li>';
}
echo '<li><p class="title">'. $row['brand'] .'</p>
<p class="type">type: 2387</p>
<p class="ez">ez: 1987</p>';
$last_vehicle = $row['brand'];
if ($row['url'] != null) {
echo '<img src="admin/'. $row['url'] .'" atl="tractor 1"/>';
}
else {
echo "there are no pictures";
}
}
}
}
else {
echo "0 results";
}

Related

PHP results not getting MySQL database

I do not understand PHP and SQL. We are just barely scraping it at the end of the semester, and its frustrating me. I am trying to get my results page to show the correct info, but for the life of me, it won't grab anything. I clearly have something wrong and was wondering if I could get some help.
Initial page
(normal top of basic webpage here)
<form id="ClubForm" action="ClubMembersResults.php" method="get">
<?php
require_once ('dbtest.php');
$query= "SELECT * FROM tblMembers ORDER BY LastName, FirstName, MiddleName;";
$r = mysqli_query($dbc, $query);
if (mysqli_num_rows($r) > 0) {
echo '<select id="memberid" name="memberid">';
while ($row = mysqli_fetch_array($r)) {
echo '<option value="'.$row['LastName'].'">'
.$row['LastName'].", ".$row['FirstName']." ".$row['MiddleName']. '</option>';
}
echo '</select>';
} else {
echo "<p>No Members found!</p>";
}
?>
<input type="submit" name="go" id="go" value="Go" />
</form>
<div id="results"></div>
</body>
results page currently written as:
<?php
$memid = 0;
$memid = (int)$_GET['memberid'];
if ($memid > 0) {
require_once ('dbtest.php');
$query = "SELECT * FROM tblMembers WHERE MemID = $memid;";
$r = mysqli_query($dbc, $query);`enter code here`
if (mysqli_num_rows($r) > 0) {
$row = mysqli_fetch_array($r);
echo "<p>Member ID: ".$row['MemID']."<br>";
echo "Member Name: ".$row['LastName'].", ".$row['FirstName']." ".$row['MiddleName']."<br>";
echo "Member Joined: ".$row['MemDt']."<br>";
echo "Member Status: ".$row['Status']."<br></p>";
}else {
echo "<p>Member not on file.</p>";
}
//table for inverntory
echo "<table border='1'>";
echo "<caption>Transaction History</caption>";
echo "<tr>";
echo "<th>Purchase Dt</th>";
echo "<th>Trans Cd</th>";
echo "<th>Trans Desc</th>";
echo "<th>Trans Type</th>";
echo "<th>Amount</th>";
echo "</tr>";
$query2 = "SELECT p.Memid, p.PurchaseDt, p.TransCd, c.TransDesc, p.TransType, p.Amount
FROM tblpurchases p, tblcodes c
WHERE p.TransCd = c.TransCd AND p.MemId = 'member id'
ORDER BY p.MemId, p.PurchaseDt, p.TransCd
";
$r2 = mysqli_query($dbc, $query2);
while ($row = mysqli_fetch_array($r2)) {
echo "<tr>";
echo "<td>".$row['PurchaseDt']."</td>;";
echo "<td>".$row['TransCd']."</td>";
echo "<td>".$row['TransDesc']."</td>";
echo "<td>".$row['TransType']."</td>";
echo "<td>".$row['Amount']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo '<p>No Member ID from form.</p>';
}
?>
the results page should be showing tables with the info in the TH and TR/TD areas. Both those areas are coming from a separate SQL table, and teh the only similar field between the tblmembers and tblpurchases is MemID.
You need to use a join in your sql request to show purchases by members.
SELECT m.Memid, p.PurchaseDt, p.TransCd,
FROM tblpurchases p join
tblmembers m on p.MemId=m.MemId
This is an example of a join

Trying to insert image from database onto news blog above each entry using PHP

I am creating a website and would like to allow an admin to add an image that is being pulled from a MySQL database and have it display above the news blog text that is being added as well. I can get it to display the images, as well as the text, but they are grouped together (images with images and text with text). How can I have my website display a the last image entered above the last text entry added?
<?php
$sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";
$result = mysqli_query($dbc, $sql);
?>
</BODY>
</HTML>
<div class="brown-container-fluid text-left">
<div class="text-home">
<h2><strong>Pine Lane News</strong></h2><br/>
<?php
if ($row = mysqli_fetch_array($result)) {
?>
<div style="text-align:center;">
<img style="max-width:300px; max-height:300px;"
src="imageView.php?image_id=<?php echo $row["imageId"]; ?>"/><br/>
</div>
<?php
}
$query = 'SELECT * FROM entries ORDER BY date_entered DESC';
if ($r = mysqli_query($dbc, $query)) { // Run the query.
// Retrieve and print every record:
while ($row = mysqli_fetch_array($r)) {
print
"<dl><dt><h3><strong>{$row['title']}</strong></h3></dt>
<dd>{$row['entry']}<br /><br />\n</dd></dl>";
}
} else { // Query didn't run.
print '<p style="color: red;">Could not retrieve the data because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
} // End of query IF.
mysqli_close($dbc); // Close the database connection.
?>
</div>
</div>
Something I came up with real quick, not tested.
<?php
while($row = mysqli_fetch_array($result)){
echo '<div style="text-align:center;">';
echo '<img style="max-width:300px; max-height:300px;"';
echo 'src="imageView.php?image_id="'.$row["imageId"].'"/><br/>';
echo '</div>';
$query = 'SELECT * FROM entries ORDER BY date_entered DESC LIMIT 1';
if ($r = mysqli_query($dbc, $query)) { // Run the query.
while ($row = mysqli_fetch_array($r))
{
print
"<dl><dt><h3><strong>{$row['title']}</strong></h3></dt>
<dd>{$row['entry']}<br /><br />\n</dd></dl>";
}
} else { // Query didn't run.
print '<p style="color: red;">Could not retrieve the data because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
} // End of query IF.
mysqli_close($dbc); // Close the database connection.
?>

unable to produce result correctly in div php

I'm not very sure how can I put them into words. I'm trying to display result in each div as shown in the image but unfortunately I'm only able to make it appear only in the "request for quote" div.
May I know where have I gone wrong?
<?php
$query2 = "SELECT * FROM client c, sales_card s WHERE c.id = s.client_id and emp_id_followup = '".$_SESSION["ID"]."'";
$result2 = mysql_query($query2);
if (mysql_num_rows($result2) > 0) {
while($row2 = mysql_fetch_assoc($result2)) {
$swimlaneID = $row2['swimlane_id'];
}
}
$query = "SELECT * FROM swimlane";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
echo '<div id="right">';
echo '<div style="border-style:solid; height:1020px;">';
echo '<h2>'. $row["swimlane_name"].'</h2>';
echo '<ul id="'. $row["shortform"].'">';
if ($swimlaneID == $row["id"])
{
echo $display-> $row["shortform"]();
}
echo '</ul>';
echo '</div>';
echo '</div>';
}
}else{
echo "no row";
}
?>

PHP, Mysql Calendar

I have created a calendar which is connected to mysql. The calendar searchs mysql and shows the number of employees on timeoff. There are several managers for a variety of employees. I created a searchterm box at which the manager can type there name and the code will query the database specific to the managers name (essentially only showing that managers employees instead of the whole company). The number of employess on time off are shown inside the calendar as a link and the total number for that specific day. Once clicked it then shows the employee names associated with the day. The problem im having is once the manager clicks onto the link, it automatically defaults to all employees instead of the ones specific to the manager. The managers search term is getting dropped and the code is defaulting back as if nothing was entered. My question is how I can reuse that searchterm over and over again until other wise directed.
$searchTerm = trim($_GET['keyname']);
if( $searchTerm != 'All Drivers' && $searchTerm != '')
{
$sqlEvent2 = mysql_query("select * FROM timeoff_365_days where (DM = '$searchTerm' or FM = '$searchTerm' or region ='$searchTerm' or location ='$searchTerm') and TimeOffDate = '".$year."-".$month."-".$i."'");
$num_rows = mysql_num_rows($sqlEvent2);
echo '<div id="button">';
echo "<a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$i."&year=".$year. "&v=false ' >".$num_rows."</a></td>";
echo '</div>';
}
else{
$sqlEvent = mysql_query( "select * FROM timeoff_365_days where TimeOffDate = '".$year."-".$month."-".$i."'" );
if (!$sqlEvent) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$num_rows = mysql_num_rows($sqlEvent);
echo '<div id="button">';
echo "<a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$i."&year=".$year."&v=true' >".$num_rows."</a></td>";
echo '</div>';
$sqlEvent = mysql_query( "select * FROM timeoff_365_days where TimeOffDate = '".$year."-".$month."-".$i."'" );
if (!$sqlEvent) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$num_rows = mysql_num_rows($sqlEvent);
echo '<div id="button">';
echo "<a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$i."&year=".$year."&v=true' >".$num_rows."</a></td>";
echo '</div>';
}
}
echo "<tr>";
echo"</table>";
?>
<div class="accordion vertical">
<ul>
<li>
<input type="radio" id="radio-3" name="radio-accordion" />
<label for="radio-3">Time Off by Driver Code</label>
<div class="content">
<?php
if(($_GET['v']==false)) {
$sqlEvent2 = "select * FROM timeoff_365_days where (DM = '$searchTerm' or FM = '$searchTerm' or region ='$searchTerm'or location ='$searchTerm') and TimeOffDate ='".$year."/".$month."/".$day."'";
$resultEvents2 = mysql_query($sqlEvent2);
while ($events2 = mysql_fetch_array($resultEvents2)){
echo $events2['DriverCode']."-";
echo $events2['Unit']."</br>";
}
}
else {
echo "";
}
?>
<?php
echo "<tr >";
var_dump($searchTerm);
if(isset($_GET['v'])) {
$sqlEvent = "select * FROM timeoff_365_days where TimeOffDate ='".$year."/".$month."/".$day."'";
$resultEvents = mysql_query($sqlEvent);
while ($events = mysql_fetch_array($resultEvents)){
echo $events['DriverCode']."-";
echo $events['Unit']."</br>";
}
}
else {
echo "";
}
echo "<tr>";
var_dump($searchTerm);
?>
GET it with $_GET, so do it in the url with domain.com/index.php?search=asddf

Basic PHP SQL Query not working

We have a basic PHP script to extract the title and description for each job from a MySQL database as simply display this information. This is what it looks like:
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
$results = mysql_fetch_assoc($query);
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$results['title']}</h2>";
echo "<p>{$results['desc']}</p>";
echo '</div>';
} ?>
Now, this only extracts one row from the database, but it should extract two. So, I tried the following to replace the while statement:
<?php foreach($results as $result) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>
This statement doesn't work either. This just displays (weirdly) the first character of each column in the first row in the table.
Does anyone have any idea as to why this isn't working as it should?
In your while use same variable $result as you started:
while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
}
and remove the first $results = mysql_fetch_assoc($query);
Result variable you have used is result not results
Replace
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
**$results = mysql_fetch_assoc($query);** // remove this line
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$results['title']}</h2>";
echo "<p>{$results['desc']}</p>";
echo '</div>';
} ?>
to
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>
You already fetched the first row before your loop started, which is why it only prints the second row. Simply comment out that line:
#$results = mysql_fetch_assoc($query); # here is your first row,
# simply comment this line
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>
You are also looping over $result but using $results in your while loop body.
Check this:
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
<?php
while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
}
?>
Change this line
<?php while($result = mysql_fetch_assoc($query)) {
to
<?php while($results = mysql_fetch_assoc($query)) {

Categories