Printing a single field below - php

Suppose I do a select like this:
select company, location, acnum, bills from table
Just how do i output data using php so that the company and location remain at the top and every bill is printed and the acnum is displayed at the bottom. I'm using mysql_fetch_assoc and have gone mad trying. I can go tru every record but cant get one at the top and bottom.
I'm trying to get data out like this:
Company name here Location here
Bill
Bill
Bill
Bill
Acnum goes here.
P.S I'm new to PHP. I used to program in ASP before.

If you have the company ID you can do something like this:
$sql = 'SELECT company, location, acnum
FROM Companies
WHERE id = '.$id
$result = mysql_query($sql);
$company = mysql_fetch_assoc($result)) {
mysql_free_result($result);
$sql = 'SELECT bills
FROM Companies
WHERE id = '.$id
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$bills[] = $row;
}
mysql_free_result($result);
echo $company['company'] . $company['location'];
foreach($bills as $bill) {
echo $bill['bills'];
}
echo $company['acnum'];

Related

How to count amount of students per university

I have a SQL database of university students, with the following details:
Table_name: register
Column_names: position, tertinst
The data in the database will look something like this:
Coach..........UCT
Athlete........Tukkies
Official.......University of JHB
Athlete........Tukkies
Athlete........Tshwane Tech
Manager........UCT
I need to count the amount of students who are athletes(position), per university(tertinst) and the output has to be something like this:
UCT.....................735
University of Jhb.......668
Tukkies.................886
this is my attempt:
$positionx = 'Athletes';
include_once 'core/includes/db_connect.php';
$sql = "SELECT tertinst, COUNT(position) FROM register WHERE position = '$positionx' GROUP BY tertinst ";
$result = $conn->query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['COUNT(tertinst)'] . '......' . $row['COUNT(position)'];
}
$conn->close();
I get no result when the code is executed and I have searched for a different solution for hours, without success.
I made a few mistakes, and corrected the syntax in the sql count, as well as the echo. Here is the solution to my problem:
<?php
include_once 'core/includes/db_connect.php';
$sql = "SELECT tertinst, COUNT(*) total FROM register WHERE position = 'Athletes' GROUP BY tertinst ";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$tertinst = $row["tertinst"];
echo $tertinst . '......' . $row['total'] . '<br>';
}
$conn->close();

how can I select and display all the rows from the same user, underneath each other with php

Users can add their workouts into a database. There will have more than one workout per user. How can i display the workout names for the logged in user, underneath each other? I have no problem adding the workouts. When I echo the names of the added workouts, it display right next to each other like "workout1workout2". I want to be able to display the workouts underneath each other. I have no idea how to do it. It would be best if I could display each workout as a button.
$query = "SELECT * FROM info WHERE username='$_SESSION[username]' ";
$results = mysqli_query($db, $query);
while($data = mysqli_fetch_array($results)) {
echo $data['workout'];
}
Firstly, you shouldn't put that username in query like that. Look into SQL Injection and how to avoid that in PHP.
As for displaying buttons/workouts. You can embed HTML code inside the echo statement like below. You can add any html like that and it will render HTML.
$query = "SELECT * FROM info WHERE username='$_SESSION[username]' ";
$results = mysqli_query($db, $query);
while($data = mysqli_fetch_array($results)) {
echo "<button>$data['workout']</button></br>";
}
$query = "SELECT * FROM info WHERE username='$_SESSION[username]' Group By username";

while loop for retrieving data

I am trying to retrieve multiple cars from a car rental database based on the model, so if someone clicks on Ford it would retrieve all cars that have a Model ID of 2 for example. The current code I have only shows the first record in the database, how do I make a while loop that would echo the rows for each match?
$ModelID = $_GET['model_id'];
$result = mysqli_query($con, "SELECT RegNumber, Colour FROM Car WHERE ModelID = '$ModelID'");
$row = $result->fetch_assoc();
echo $row["RegNumber"];
echo $row["Colour"];
You need something like:
while ($row = $result->fetch_assoc()) {
echo $row['RegNumber'];
echo $row['Colour'];
}
For more details, please go through the PHP Documentation
One possible solution is using mysqli::query. And never forget to escape data inside the query, in that case you should use mysqli::real_escape_string function
$escapedModelId = $mysqli->real_escape_string($ModelID);
$query= "SELECT RegNumber, Colour FROM Car WHERE ModelID = '$escapedModelId'";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row["RegNumber"];
echo $row["Colour"];
}
}

mySQL database: printing specific row or rows from a db table

please assist. i have a database with a couple of tables and rows and i want the php to print specific rows as and when i want it to. at the moment it renders all the content of the spesific table on my webpage. in future, i would like it to display the contents of a specific table if a cirtain user is logged in so im going to do that when i understand if statements and get over this hurdle 1st. my code is as follows:
<?php
include 'connect-mysql.php';
echo "<br/>";
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}
?>
To fetch specific rows from a table you have to include a WHERE clause in your SQL statement.
For example:
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer WHERE customer_id = 2";
Match the WHERE xxxxx clause to any column in your table
You need to specifiy yor criteria as a where clause in the SQL
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer where RAMSCODE = %1";
$result = mysql_query($query,mysql_real_escape_string($yourcode)) or die (mysql_error());
Also you really need to Read the Manuals!
As far as i've get what you want is to display only that row from customers table, which customer is logged in. you can use some thing like this:
while($row = mysql_fetch_array($result))
{
if($row['CUSTOMER_NAME'] == " //Customer Logged In (customer name from session)"){
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}else{
//do nothing or continue with printing all
}
}
Hope this helps.

Grouping a list of names by country using PHP and MySQL

I have a MySQL database containing a person's forename, surname, their country, and whether they are happy for their name to be listed on a website.
The field names are 'firstname', 'lastname', 'country' and 'listedagree'. In the database, the 'listedagree' result is either Y or N.
I'd like to list only the people that have agreed to have their names listed, grouped by country, and ordered by their surname
For each country, the outputted markup should look like this:
<h4>Country name</h4>
<ul>
<li>Amy Adams</li>
<li>Kenneth Branagh</li>
<li>Ray Charles</li>
</ul>
My PHP skills are very limited - I'm really struggling to find the code I need to get this working. Can anybody help please?
Many thanks in advance!
SELECT * FROM users WHERE listedagree = 'Y' ORDER BY country, lastname, firstname
Then with your PHP loop through the records. Every time the country name changes close the preceeding ul and add a h4 and opening ul before echoing the users name. eg:
<?php
$country = null;
while($row = mysql_fetch_assoc($result)) {
if($row['country'] != $country) {
if(!is_null($country)) {
echo '</ul>';
}
$country = $row['country'];
echo "<h4>$country</h4>";
echo '<ul>';
}
echo "<li>{$row['firstname']} {$row['lastname']}</li>";
}
echo '</ul>';
This code assumes that your country name data is clean and you don't have things like UK and United Kingdom or USA and United States of America in the database.
I wrote example code :)
<?php
$result = mysql_query("SELECT country FROM tablename group by country")
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$country = $result['country'];
$result2 = "SELECT country FROM tablename where country = '$country' and listedagree = 'y' order by surname";
echo '<h4>'.$country.'</h4>';
echo <ul>;
while($row2 = mysql_fetch_array( $result2 )) {
echo '<li>'.$row2["firstname"].' '.$row2["lastname"].'</li>';
}
echo '</ul>';
}
?>
You need to do two thing, first is an SQL query to retrieve the values, you can do something like:
SELECT firstname,lastname,country FROM TABLE WHERE listedagree='Y' ORDER BY country
When you retrieve the data on PHP you need to iterate over it, keeping the actual country in a temp variable to be able to detect when it changes, for example you can do something like:
//Conect to the database
mysql_connect("hostaddress.com", "username", "password") or die(mysql_error());
//Selet the database to work with
mysql_select_db("Database_Name") or die(mysql_error());
$sql = "SELECT firstname,lastname,country FROM TABLE WHERE listedagree='Y' ORDER BY country";
//retrive the data
$result = mysql_query($sql) or die(mysql_error());
//Now iterate over the result and generate the HTML
$html = '';
$tmp_country = '';
while($data = mysql_fetch_array( $result ))
{
//If the country have changed
if($tmp_country != $data['country'])
{
//Check if we need to close the UL
if($tmp_country != '') {$html .= "</ul>"};
//Print the country header
$html .= "<h4>$data['country']</h4>";
$htm l .= "<ul>";
//store the last country
$tmp_country = $data['country'];
}
//Add the names to each country
$html .= "<li>$data['firstname'] $data['lastname']</li>";
}
//Close the last UL
$html .= "</ul>";
I couldn't try the code so maybe it need some fine tuning to get it working but the it will do the job, if you have any problems let me know and I will help you.

Categories