Need to showup the Qty of "IDs" or "Class" from a Site in my header.
It a job-site, i want to count the IDs or class of my Job Listings and show the number in my header (Menu).
How is it possible? With "getElementsByTagName" it works like a charme. Tried with "H3" Tags, but i have to many h3 on the site, so the qty / number is not correct.
my code now:
<?php
$htmlString = file_get_contents('https://www.mywebsite.de/unternehmen/jobs/');
//Create a new DOMDocument object.
$htmlDom = new DOMDocument;
//Load the HTML string into our DOMDocument object.
#$htmlDom->loadHTML($htmlString);
//Extract all h3 elements / tags from the HTML.
$h3Tags = $htmlDom->getElementsByTagName('h3');
$jobanzahl = $htmlDom->getElementById('jobtitel')->nodeValue;
echo "Total H3 Tags: ". count($h3Tags)."<br/>";
It would be much easier to use the SELECT COUNT with your database, because you can manage which job offers are active and which are not. You can also ORDER BY starting date if you wish !
Here is the dataset I used for this example :
Each job has a unique id (int) as a primary key, a title (varchar), a description (text), a starting date (date) and a status (active or not - boolean). You can archive inactive offers for monthly or yearly reports, but you must count only active ones.
At first, I display the offers on a very basic html page :
$sql = "SELECT * FROM job";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
echo "<h1>JOBS</h1>";
echo "<br>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "<p><small>Starting on : " . $row['start_date'] . "</small></p>";
echo "<hr>";
}
}
And then, I count and display the number of active offers :
$sql = "SELECT COUNT(*) AS c FROM job WHERE isActive = 1";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<p>There are " . $row['c'] . " offers</p>";
}
Here is the final result :
Finally, you should look at this codepen to circle the result :
https://codepen.io/jnbruno/pen/vNpPpW
Related
Is it possible to number rows in mysql using php? So not like with auto increment but with some type of code? I can do num_row() but it displays numbers based on how data is sorted in the table... but i would like data to be sorted by size for example, but numbered from 1 - oldest to X -newest.
I would actually like to manually give rows numbers... For example all inputs with id 10 should be numbered from 1-10 etc. (because i output data based on id)...
I tried with auto increment of a number but since all data is written in the same table, numbers dont go from 1 but from where it stopped (i deleten rows before) ... I need every output i do on a page to be numbered from 1-X.
To sum it up, i just want to create a counter to simulate an ordered list in a table, but every output should be numbered and then sorted by size:
I simulated what it should look like bellow:
if(!empty($_GET["orderby"])) {
$orderBy = $_GET["orderby"];
}
if(!empty($_GET["order"])) {
$order = $_GET["order"];
}
$randomNum = substr(str_shuffle("0123456789"), 0, 4);
$conn = mysqli_connect("localhost", "owjej_david", "dadadada", "owjej_kalkulator");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT dolzina, sirina, kolicina, opombe, povrsina, id, narocilo, cas FROM zunanje where id='$id' ORDER BY " . $orderBy . " " . $order;", cas asc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rowNumber=0;
// output data of each row
while($row = $result->fetch_assoc()) {
$rowNumber++;
echo "<tr><td>" .
$rowNumber. "</td><td>" .
$row["dolzina"] ." cm".' ✎'. "</td><td>" .
$row["sirina"]." cm".' ✎'. "</td><td>" .
$row["kolicina"].' ✎'. "</td><td>" .
$row["opombe"].' ✎'. "</td><td>" .
$row["povrsina"]." m²".' ✎'. "</td><td>" .'
X'."</td></tr>";}
echo "</table>";
}
$conn->close();
?>
You could try this approach:
Select the rows from the database ordered by date (oldest to newest)
use
fetch_all
to get all result rows
preserve the relative row number
use
array_multisort
to sort by size. (Example #3 is of particular interest)
This example demonstrates the idea, where $rows represents the result set from fetch_all:
$rows = [['id'=>10,'size'=>10],
['id'=>10,'size'=>1],
['id'=>10,'size'=>7],
['id'=>10,'size'=>5],
['id'=>10,'size'=>2],
];
print_r($rows);
for ($i=0;$i<count($rows);$i++) { // This loop preserves the relative row number
$rows[$i]['rowid'] = $i + 1;
}
$size = array_column($rows,'size');
array_multisort($size,$rows);
print_r($rows);
Then change the while loop to a foreach ($rows as $row) and you should achieve the desired result.
everyone. I'm having a bit of a PHP conundrum here and I couldn't find a good answer that already existed. You see, I'm working on a project where I have to take a classmate's discography website and revamp it with PHP, to where, instead of having the album covers and tracklists hard-coded in, it would query the database for them. My problem is that I have to keep the general style of his site intact, and I'm having trouble doing that. Basically his styles depend on having the album cover, name, and tracklists in div tags, and the style he's got in place is achieved through both Bootstrap and his own, custom CSS stylesheet.
Before I start to ramble, my question is: is there any way to wrap looping output in HTML tags? I need to get the album cover, album name, and tracklists in a div tag, but only the tracklists loop. Here is the code I have in place to query the database:
<?php
require ('mysqli_connect.php');
// Connect to database server
mysql_connect("localhost", "admin", "instructor") or die(mysql_error());
// Select database
mysql_select_db("phprediscography") or die(mysql_error());
// SQL query
$q = "SELECT DISTINCT albums.albumname, albums.albumID, albums.coverart
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID"; //select UNIQUE results from database
$t = "SELECT trackname FROM tracks WHERE albumID = 1";
$b = "SELECT trackname FROM tracks WHERE albumID = 2";
$n = "SELECT trackname FROM tracks WHERE albumID = 3";
$r = "SELECT trackname FROM tracks WHERE albumID = 4";
$result = mysqli_query($dbcon, $q);
$result1 = mysqli_query($dbcon, $t);
$result2 = mysqli_query($dbcon, $b);
$result3 = mysqli_query($dbcon, $n);
$result4 = mysqli_query($dbcon, $r);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //loop through database to get each album
echo '<img class="img-responsive" src=' . $row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
if ($row['albumID'] == 1) {
foreach($result1 as $row1) { //loop through tracks and output to page
echo '<p>' . $row1['trackname'] . '</p>';
}
}
if ($row['albumID'] == 2) {
foreach($result2 as $row2) { //loop through tracks and output to page
echo '<p>' . $row2['trackname'] . '</p>';
}
}
if ($row['albumID'] == 3) {
foreach($result3 as $row3) { //loop through tracks and output to page
echo '<p>' . $row3['trackname'] . '</p>';
}
}
if ($row['albumID'] == 4) {
foreach($result4 as $row4) { //loop through tracks and output to page
echo '<p>' . $row4['trackname'] . '</p>';
}
}
}
// Close the database connection
mysql_close();
?>
If I need to post anything else, let me know, this is my first-ever question so I'm just kind of feeling it out.
By doing your $t = "SELECT trackname FROM tracks WHERE albumID = #"; and if($row['albumID']==#) you are essentially still hardcoding similar to your friend. Just do 1 query, where you join all the tracks. Then when looping, group by the albumname -
<?php
require('mysqli_connect.php');
// SQL query
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$current_albumID = ""; //create current albumID var to be used below.
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){//loop through database to get each album
if($row['albumID'] != $current_albumID){
echo '<img class="img-responsive" src='.$row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
$current_albumID = $row['albumID']; // set current albumID to this albumID
}
echo '<p>' . $row['trackname'] . '</p>';
}
?>
Try something like this instead: Get all the data you're after in your first query, then use php to process that into your output:
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$lastAlbumId = null;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
if ($lastAlbumId != $row['albumID']) {
echo '<img class="img-responsive" src="'.htmlentities($row['coverart']).'"><br />';
echo '<h2>'.htmlentities($row['albumname']).'</h2><br />';
}
echo '<p>'.htmlentities($trackname).'</p>';
$lastAlbumId = $row['albumID'];
}
A few things to note:
I added use of htmlentities to escape the user data so malicious people can't type in HTML somewhere and have it appear on your site. This is something you should do almost everywhere you're displaying data from a database in a html site, except for very rare cases where you know what you're doing.
You probably don't need those <br /> tags - <h2> is a block level element so it'll force itself onto it's own line anyway (unless there's some silly CSS rules somewhere).
Also note - the above code is untested - typed straight into browser. There may be some syntax errors - let me know if you see any problem and I'll happily edit the answer. (or you can suggest an edit).
I have some code where I want it to only show rows where there is a certain string in a column. I have a column called "Tags" where it has tags in this format "tag1, tag2" Etc. I want to have links so people can only show products with a certain tag. This is where I run into problems. I can't get it to show rows with certain tags, it shows every row.
<?php
try {
//open the database
$db = new PDO('sqlite:prodDb.sqlite');
$tag = $_POST['tag'];
if (isset($tag)) {
$result = $db->query('SELECT * FROM Products WHERE instr(Tags, $tag) > 0');
} else {
$result = $db->query('SELECT * FROM Products ');
}
//now output the data to a simple html table...
$result = $db->query('SELECT * FROM Products');
foreach ($result as $row) {
print "" . $row['Id'] . "<br />";
print "" . $row['Name'] . "<br />";
$tags = explode(', ', $row['Tags']);
foreach ($tags as $tag) {
print "Tag: " . $tag . "<br />";
}
print "" . $row['Link'] . "<br />";
print "" . $row['Screenshot'] . "<br />";
print "" . $row['Download'] . "<br />";
}
// close the database connection
$db = NULL;
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
Any ideas where I went wrong?
Get rid of the $db->query line here:
//now output the data to a simple html table...
$result = $db->query('SELECT * FROM Products');
You're discarding the results from the query that matched the tag, and using this query that returns all products.
In the query with the tag, you have a syntax error, because you need quotes around the string. It would be better to use a prepared query:
$stmt = $db->prepare('SELECT * FROM Products WHERE INSTR(Tags, :tag)');
$stmt->execute(array(':tag' => $tag));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Also, if you have all the tags in a single column, you have a poor table design. You should normalize your data by moving the tags into a separate table, with one row per tag for each product.
It probably doesn't work because here:
//now output the data to a simple html table...
$result = $db->query('SELECT * FROM Products');
You are simply selecting all products and ignoring the previous query/filter.
New to php environment, what I am trying to do is create a list using php and MySQL database. see below
-----my output requirements info ------
main page heading
subheading1 (content of brandtype=1)
1111
2222
3333
4444 ( I want these as a hyperlink to open in the same webpage)
subheading2 (brandtype=2)
5555
6666
7777
8888 ( I want these as a hyperlink to open in the same webpage)
my code below
// Connect to database server
include 'xxxxxyyyyzzzz.php';
$conn = mysql_connect($db_host,$db_username,$db_password);
mysql_connect($db_host,$db_username,$db_password) or die (mysql_error ());
mysql_select_db($db_database,$conn) or die(mysql_error()); // Select database
echo "<h1>main webpage heading</h1>";
echo "<h3>my subheading</h3>";
// SQL query
$strSQL = "SELECT * FROM table name WHERE brand type='1','Software' ORDER BY serviceName ASC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
$strName = $row['serviceName'];
$strLink = "<a href = 'person.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
// include 'emaild.php';
}
// Close the database connection
mysql_close();
?>
</ul>
</body>
</html>
end of my code
I am getting a listing ok, but have to put in subheading manually (e.g. echo "main title page names"; echo "subheading title"; depending on the brand type ?
how can tweak my code so that where my brand type = 1 it prints a heading brand type1 and then prints out the items for that brand 1 underneath it, if there are no items , then it does not print subheading (brand type=1) and goes to the next to print subheading for brandtype=2 and lists the content underneath it.
I can make list items underneath each subheading as links to a webpage but it does not work, how can I make these list items open on the same webpage with more details of product and I would use back button to go previous list webpage...thanks in advance..singhy
Are the brand names in a different table where it can be read? If it's not you can do it manually still, but will much more ease (See below). If so, please let us know where that is located.
SendBrandListings(1, "Brand 1 Header");
SendBrandListings(2, "Brand 2 Header");
function SendBrandListings($brandId, $heading){
echo "<h3>$heading</h3>";
$strSQL = "SELECT * FROM table name WHERE brand type='$brandId','Software' ORDER BY serviceName ASC";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)) {
$strName = $row['serviceName'];
$strLink = "<a href = 'person.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
echo "<li>" . $strLink . "</li>";
}
}
UPDATE
If your brand name is in the same table, let's say the field is brandName - you would modify you current loop to this (simplified for demo purposes).
First, you'll want to ensure that your results are sorted by Brand FIRST, then by service name. This is because we will be looping through the services in the order they are received in. This will arrange items of a like brand together. So make sure your SQL statement's sorting argument looks like this:
ORDER BY brandName, serviceName ASC
Simply keep track of the last Brand Name you displayed, and if it changes, display the new one.
$c = 0; //Variable to keep count of categories
$lastBrand = ''; //Declare a variable to track the last displayed Brand Name
while($row = mysql_fetch_array($rs)) {
//If the brand name has changed, display it and update the tracking variable
if ($lastBrand != $row['brandName']){
$lastBrand = $row['brandName'];
//If this isn't the first category, end the previous list.
if ($c>0) echo "</ul>";
echo '<h3>'.$row['brandName'].'</h3><ul>';
$c++;
}
$strName = $row['serviceName'];
$strLink = "<a href = 'person.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
echo "<li>" . $strLink . "</li>";
}
I have got one piece of code which gives me a list of all the column names for a specific table. Can i use this list as my $row['VARIABLE'] instead of specifying every row?
The current output of the table names can be seen here this is the second paragraph of text, the first ones are my table names (USERS, ADMIN_LOGIN)
I am working on making a small script which will list all the table contents of a table but it is likely the table will change often so i want a script which can auto generate the table of contents without me having to manually re-enter it all as i have done in the second piece of code below?
Thanks guys
<?php
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
echo $table['name'] . '<br />';
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
echo "ID = ". $row['ID'] . "\n";
echo "USERNAME = ". $row['USERNAME'] ."\n";
echo "AGE = ". $row['AGE'] ."\n";
echo "LOCATION = ".$row['LOCATION'] ."\n\n";
echo "ANYTHING_ELSE = ". $row['ANYTHING_ELSE'] . "\n";
echo "EMAIL = ". $row['EMAIL'] ."\n";
echo "PROFILE_APPROVED = ". $row['PROFILE_APPROVED'] ."\n";
echo "NUMBER_OF_BATTLES = ".$row['NUMBER_OF_BATTLES'] ."\n\n";
echo "TOTAL_WINS = ".$row['TOTAL_WINS'] ."\n\n";
}
?>
Yes, you can use variables for the index values of an array. For example,
$row = array('col_name' => 'column value');
$index = 'col_name';
echo $row[$index]; // Equivalent to $row['col_name']. Prints "column value"
You should be able to accomplish what you want pretty easily using the above logic. Basically just store the column names from the first query into an array, then loop through that array to get the column names each time you print a row.
Give this a try:
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
foreach ($columns as $col)
echo $col . " = " . $row[$col] . "\n";
}
I use the following in order to get a list of columns names in the order they are defined in the table. I use it to populate an insert/select when preserving data.
sel columnname
from dbc.columns
where databasename='databasename'
and tablename='tablename'
order by columnid;