I am working on job portal project, and want to arrange values alphabetically according to their starting alphabet section, I want companies starting with A to be under the A column header, and companies starting with B to be under the B header..."
or if i have no companies with the value of B then B be skipped.
<span>a</span>
<?php
$sql = "select * from companies";
$result = mysqli_query($con, $sql);
while($data = mysqli_fetch_array($result)) {
$company = $data['company_name'];
?>
<div class="list-col"> <?php echo $company; ?>(0) </div>
<?php
}
?>
</div>
</li>
<!-- Sample of how column in HTML -->
<li class="loop-entry">
<div class="col">
<span>C</span>
<div class="list-col">
Company Name (0)
Company Name (1)
Company Name (2)
Company Name (3)
Company Name (4)
</div>
</div>
</li>
i wants to arrange according to this image
Okay here it is. I used functions to capture what you wanted. I will detail more later to explain things that you need to understand.
I completed an example on PHP Sandbox with an array of values to display the code as outputted in text in HTML
<?php
$sql = "select * from companies ORDER BY company_name";
$result = mysqli_query($con, $sql);
$letter = '';
$count = 0;
while($data = mysqli_fetch_array($result)) {
$company = $data['company_name'];
createCompanyList($company, $letter,$count);
}
/**
creates Company Listing
*/
function creatCompanyList($company, &$letter, &$count){
if($letter !== $company[0]) {
if($count >0) {
endCompanyList();
$count = 0;
}
$letter = $company[0];
startCompanyList($letter, $count);
}
//only adds the company if the letter and company matches
//and permits only the first 5 companies
if($letter == $company[0] && $count <= 4) addCompanyList($company);
if($count==4) endCompanyList();
$count++;
}
//creates opening divs for a Company List based upon letter
function startCompanyList($letter, &$count){
?>
<li class="loop-entry">
<div class="col"> <span><?=$letter?></span>
<div class="list-col">
<?php
}
//closes divs for the Company List
function endCompanyList(){
?>
</div>
</div>
</li>
<?php
}
//inserts company into to a column
function addCompanyList($company){
?>
<?=$company?>
<?php
}
?>
Related
I am working on creating a drop down button that lets one select the year from a list of options in order to sort through a data table. The code (reproduced below) keeps repeating the last year available, I can't seem to figure out why it is doing this. I am using PHP to pull from a MySql database.
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Select Year</button>
<div id="myDropdown" class="dropdown-content">
<?php
$year = array();
while($subject = mysqli_fetch_assoc($subject_set)) {
$i=0;
$exists = 0;
$n = count($year);
while($i < $n){
if ($subject['year'] == $year[$i]){
$exists = 1;
}
$i++;
}
if($exists == 0){
$year[$n] = $subject['year'];
echo " {$subject['year']} ";
}
}
$subject_set = find_all_subjects();
?>
</div>
</div>
In my 'magnums' table I have the following data:
What I want is to display the producer as a title and then the corresponding rows under that heading underneath that. My desired output:
I'm very new to PHP and mysql so I'm not sure how to go about this but this is what I have so far:
Model:
class Magnum_model extends CI_Model {
public function get_magnum_wines() {
$query = $this->db->query('SELECT * FROM magnums');
return $query->result();
}
}
Controller:
public function index() {
$data['magnums']= $this->Magnum_model->get_magnum_wines();
$this->load->view('magnums.php',$data);
}
View:
<h3>Domaine Vincent Rapet</h3>
<?php foreach($magnums as $magnum): ?>
<div id="magnum-img">
<div class="gallery">
<img src="/BurgundyDirect/gallery/<?php echo $magnum->Image; ?>">
</div><!-- gallery ends -->
<div class="desc">
<div id="wine-name">
<h5><?php echo $magnum->Name_of_wine; ?></h5>
</div>
<h6><?php echo $magnum->Producer; ?><h6>
<h4><?php echo $magnum->Magnum_price; ?></h4>
</div>
</div>
<?php endforeach; ?>
The output of the above code:
I don't know how to sort it to my desired output. Any help would be much appreciated and thank you in advance :)
If you need to show groups of products, you can get list of producers of producers and related products in controller.
In your producers model, create method, that get all producers (select * from producers).
Get producers in controller $producers = $this->Producer_model->get_producers();
Then create array with producer's name and products.
sample code:
$producerWithProducts = array();
foreach($producers as $producer) {
$producerId = $producer->Id;
$producerWithProducts[$producerId]['producerName'] = $producer->Name;
$producerWithProducts[$producerId]['products'] = $this->Magnum_model->get_magnum_wines_by_producer_id($producerId);
}
Then pass $producerWithProducts in template and iterate it.
I had the same thing but with wine categories / colours so this is what I did:
First make a new table called producers with 2 columns: id and name.
In the wine table make a new column with the name producer_id.
The value of this column is corresponds with the id in the producers table.
Then you can iterate through it like this:
function extractWines() {
$producers = mysqli_query("SELECT id FROM producers");
foreach($producers as $key => $value) {
$query = mysqli_query("SELECT * FROM wines WHERE producer_id = " . $value . "");
$rowname = mysqli_fetch_assoc($query);
$html = <<<HTML
<h1>{$rowname['producer']}</h1>
HTML;
echo $html;
while($row = mysqli_fetch_assoc($query)) {
$html = <<<HTML
(html code of the item with styling)
HTML;
echo $html;
}
}
}
This should help you with your problem.
I am trying to make a page which has to get data from two tables. and display on a page. this displayed data is an array. for example if the displayed data is say USA which come from Table A,and if you click on USA...then it should go to Table B and get all the states from Table B related to USA and display it on the page. so how to join the tables?
the code used is as below:
<?php
require("libs/config.php");
$pageDetails = getPageDetailsByName($currentPage);
$stateDetails = getStateDetailsById($page_id);
include("header.php");
?>
<div class="row main-row">
<div class="col-md-8">
<section class="left-content">
<h2><?php echo stripslashes($pageDetails["page_title"]); ?></h2>
<?php echo stripslashes($pageDetails["page_desc"]); ?>
<!--New-->
<?php
$page_id = $pageDetails["page_id"];
if ($_GET["id"] <> "")
{
// if we are on page.php page. get the parent id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_PAGES . " WHERE status = 'A' AND parent = :parent ORDER BY sort_order ASC";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($pageDetails["parent"]));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
elseif ($page_id <>"")
{
// On any other Page get the page id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_PAGES . " WHERE parent = :parent";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($page_id));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
?>
<div class="col-sm-12">
<?php
if (count($pageResults) > 0)
{
?>
<section>
<h2>States</h2>
<div>
<div class="row">
<?php foreach ($pageResults as $rs)
{ ?>
<div class="col-sm-3">
<ul class="state">
<li class="state">
<div class="state-dist"><h3><?php echo stripslashes($rs["page_title"]);?></h3>
<div class="state_img"><img src="images/<?php echo stripslashes($rs["page_image"]);?>"height="50" width="180"</div>
<br />
<br />
<div class="page-actions">
More Details
</div>
</li>
</ul>
</div>
<?php } ?>
</div>
</div>
</section>
<?php } ?>
</section>
</div>
So,
when i click on the link created by the last part of the code then it should go to TABLE.STATES fetch the records and display it. Currently this code goes to the same table TABLE_PAGES.
I know i have to use table joins but I am not able to code it.
Currently this code goes to the same table TABLE_PAGES.
As far as I think, you should change TABLE_PAGES to TABLE_STATES in the following part of your code:
elseif ($page_id <>"")
{
// On any other Page get the page id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_STATES . " WHERE parent = :parent";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($page_id));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
I'm assuming you'll be running the following SQL code:
SELECT * FROM TABLE_STATES WHERE TABLE_STATES.page_id = TABLE_PAGES.page_id
which you can execute to get a list of all the states belonging to the parent (TABLE_PAGES) table.
TIP: Always try to use table names that represent real-world entities AND serve the purpose of the actual data that you want to store. In your case TABLE_COUNTRIES would be a more conventional name for a table that represents the entity country.
You could also run a left join as such:
SELECT TABLE_STATES.* LEFT JOIN TABLE_COUNTRIES ON TABLE_COUNTRIES.page_id = TABLE_STATES.page_id AND TABLE_COUNTRIES.page_id = <your provided value>
I am trying to figure out why my mysqli query is not returning all the rows. For some reason it returns 3 results when there are 4 in the database. It is completely skipping the first record in the database. Here is my query.
$results = "SELECT * FROM `results` LIMIT 10";
$result = $conn->query($results);
if ($result) {
?>
<div id="tableResults">
<div class="row1 bg">Predicted Sex</div>
<div class="row2 bg">Suggested Baby Boy Name</div>
<div class="row3 bg">Suggested Baby Girl Name</div>
<div class="breaker"></div>
<?php
/* fetch object array */
$i = 0;
$count = count($result->fetch_array());
while ($row = $result->fetch_array()) {
?>
<div class="row1 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['sex']; ?></div>
<div class="row2 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['boy_name']; ?></div>
<div class="row3 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['girl_name']; ?></div>
<?php
$i++;
}
}
$conn->close();
?>
As was stated in the comments $count = count($result->fetch_array()); this will not work as expected and makes you lose one row (as it has been fetched). Instead you can use num_rows like the following
$count = $result->num_rows;
while ($row= $result->fetch_array()) {
//...
}
To go into detail, when you read the manual on fetch_array(), you'll find this part
mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both
A result row (in words: one) will be fetched any time this function is called. So currently your code is similar to:
fetch one row -> do nothing with it
while:
fetch one row -> display it
I have been trying for a while to figure out how to display data from a specific row within my database based on the ID.
Say I want the link to be survivaloperations.net/page/mso?p=contracts&id=#
where id=# is the ID of the row I am pulling data from in the database
How would I pull and display data from the database using a link like shown above?
I Tried to google it, but didn't really know what to google to find related things
Any help or links for references are appreciated!
Here is what I had tried:
<?php
if ($p == contracts) {
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
if ($id != 0):
// I assume this is a specific news item meaning you know it's ONE result
$query = 'SELECT * FROM contracts WHERE id=' . $id . ' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
endif;
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while ($row = mysql_fetch_array($result)) {
// and use'em however you wish
echo("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row2[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a
href='#'>$row2[unit]</a><br/>by: <a
href='http://www.survivaloperations.net/user/$row2[userid]-$row2[username]/'>$row2[username]</a>
</div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row2[callsign]<br/>
Urgency: $row2[urgency]<br/>
Location: $row2[location]<br/>
Grid: $row2[grid]<br/>
Enemy Activity: $row2[enemy_activity]<br/>
Hours Since Lasrt Contact: $row2[contact_hours]<br/><br/>
Supplies Requested: $row2[supplies]<br/>
Comments: $row2[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
?>
I figured it out with my original code:
if ($p == contracts)
{
$cid = $_GET['id']; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
$query = 'SELECT * FROM contracts WHERE id='. $cid .' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while($row = mysql_fetch_array($result)){
// and use'em however you wish
echo ("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a href='#'>$row[unit]</a><br />by: <a href='http://www.survivaloperations.net/user/$row[userid]-$row[username]/'>$row[username]</a></div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row[callsign]<br />
Urgency: $row[urgency]<br />
Location: $row[location]<br />
Grid: $row[grid]<br />
Enemy Activity: $row[enemy_activity]<br />
Hours Since Lasrt Contact: $row[contact_hours]<br /><br />
Supplies Requested: $row[supplies]<br />
Comments: $row[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
Google for $_GET variable in PHP and have a look at database connection using PDO or mysqli
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/pdo.query.php
After you added code:
mysql_* is deprecated. Try to switch to either mysqli or PDO and have a look at the link above.
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) ? abs( (int) $_GET['id']) : 0;
if($id == 0) {
echo 'Invalid ID';
return;
} else {
$query = "SELECT * FROM `table` WHERE `id`=". $id;
$get = $db->prepare($query);
if($get) {
$get = $db->query($query);
$r = $get->fetch_array(MYSQLI_ASSOC);
var_dump($r);
} else {
echo 'Could not connect to the database';
return;
}
I've mixed two styles of MySQLi, which isn't really standard, but it should suffice for this example.
http://php.net/mysqli
(Ensure you have database connection)
$row2 should be $row
And things like
$row[contract_type]
Better to be
$row['contract_type']
And try to move to mysqli or PDO as advised by earlier poster