PHP MYSQL while change field name each time - php

I have a database to store people's quick links. This is a very basic quick link storage method. The database looks like this:
full_name | 1url | 1name | 2url | 2name | 3url |3 name | 4url |4name | 5url | 5name
^This goes on until 10. I know this is a bad way, but this is for an unprofessional website.
I will want to put the result into an ordered list. But I am unsure how to change the number (1url or 2url) each time?
So currently I have it set up like this in PHP
$result = mysql_query(SELECT * FROM `links` WHERE `full_name`='$loggedin')or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo '<li><a href="';
echo $row['1url'];
echo '"></a></li>';
}
But I am having no luck with that! I'm very unsure of what I should do. I want it to display another <li> with an <a> and the link plus name of the link for each row found.
Thanks! Please be specific with me, as this is new ground! :D
EDIT:
I have also run into another problem. I have used code from peoples' answers and most of them work. However, If one of the fields is blank (so a user has only 6 quick links) it still shows an <li>. Now I can't see anyway round this issue. :/
SOLUTION:
Here is what works:
while($row = mysql_fetch_array($result)){
for($i = 1; $i < 10; $i++) {
if(!trim($row[$i . 'url'])=='') {
echo '<li><a href="';
echo $row[$i . 'url'];
echo '">';
echo $row[$i . 'name'];
echo '</a></li>';
} //end of didn't trim
}//end for for
}//end of while

$result = mysql_query("SELECT * FROM `links` WHERE `full_name`='$loggedin'")or die (mysql_error());
while($row = mysql_fetch_array($result)){
for($i = 1; $i < 10; $i++)
{
echo '<li><a href="';
echo $row[$i . 'url'];
echo '"></a></li>';
}
}
Mind you, this is pretty hacky... I would have just implemented it with 3 columns (maybe 4 using an autoincrement to sort) and then select the rows based on the user, emitting each row. That removes the 10 url limit.
Edit
For your second question, have a look at the PHP 'empty' function and break/continue the loop if the function returns true.

It would be a lot cleaner and easier to change your database setup a little bit. You could have two tables:
users
id: a unique ID for each user, probably an auto increment int of some sort
full_name: just as you've used it in your table
quick_links
id: quick link id, probably an auto increment int (or you could do a primary index on user_id+order)
user_id: the user ID to tell us who this quick_link belongs to
name: the name of the quick link
url: the url of the quick link
order: what order to show this link in
Then you can simply do something like
$userid_result = mysql_query(
"SELECT `id` from `users` WHERE `full_name` = $loggedin;"
);
$row = mysql_fetch_row($userid_result);
$userid = $row[0];
$links_result = mysql_query(
"SELECT * from `quick_links` WHERE `user_id` = $userid ORDER BY `order` ASC;"
);
while($quick_link = mysql_fetch_object($links_result))
{
printf("<li>%s</li>", $quick_link->url, $quick_link->$name);
}
Of course you'd need some error checking in there, but that gives you an idea.

You need to put some double quotes around your select statement:
$result = mysql_query("SELECT * FROM `links` WHERE `full_name`='$loggedin'") or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo '<li><a href="';
echo $row['1url'];
echo '"></a></li>';
}

while ($row = mysql_fetch_array($result))
{
$full_name = array_shift($row);
for ($i = 0; $i < 10; ++$i)
{
echo '<li><a href=' . htmlspecialchars(array_shift($row)) . '>';
echo array_shift($row);
echo '</a></li>';
}
}
array_shift returns the first element from an array and removes it from the array at the same time. So the code above removes the full_name field from the record and then iterates over the rest of the record, removing and printing a URL and its corresponding name on each iteration.
htmlspecialchars is used to ensure that a valid a-tag is created. Depending on where the name of the link comes from, it should also be used on the name of the link.

You SQL query needs to be passed as a string enclosed in "...":
$result = mysql_query( "SELECT * FROM `links` WHERE `full_name`='$loggedin'" )
or die (mysql_error());
$i = 0;
while($row = mysql_fetch_array($result)){
$attributeURL = $i . 'url';
$attributeName = $i++ . 'name';
echo '<li>'
. '' . $row[ $attributeName ] . '
. '</li>'
;
}

Related

Count "getElementById" in PHP

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

Is it possible to wrap looping PHP output in tags?

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

Facing difficulty in pagination using php mysql

I am showing results arranged in table from mysql database using php, but I am not being able to find a way to paginate my results, because of the data being arranged in table and because some of the rows are missing and as webpage will be dynamic so user will be able to delete rows and insert new rows again and again, so because of that I can't get my results paginated using auto_increment value as well.
Following is my script:
<?php
$mysql_session = mysql_query("SELECT * FROM session");
$no_of_rows_session = mysql_num_rows($mysql_session);
$msg_session='';
$last_row = mysql_query("SELECT * from session ORDER BY id DESC LIMIT 1");
$last_id = '';
while($select_id_of_last_row = mysql_fetch_array($last_row)) {
$last_id = $select_id_of_last_row['id'];
}
?>
<?php echo $msg_session; ?>
<?php
if($no_of_rows_session < 1) {
$msg_session = 'No Session has been added yet';
} else {
for($i = 1; $i<=$last_id; $i++) {
${'mysql_session_every_single_query_' . $i} = mysql_query("SELECT * FROM session WHERE id LIKE '%$i%'");
${'mysql_existance_of_session_id_' . $i} = mysql_num_rows(${'mysql_session_every_single_query_' . $i});
while(${'mysql_every_session_data_' . $i} = mysql_fetch_array(${'mysql_session_every_single_query_' . $i})){
${'id_session_' . $i} = ${'mysql_every_session_data_' . $i}['id'];
${'session_start_' . $i} = ${'mysql_every_session_data_' . $i}['start'];
${'session_end_' . $i} = ${'mysql_every_session_data_' . $i}['end'];
echo "<table>";
echo "<tr id='tr_session_hover_" . $i . "'
class='tr_session_hover'
onClick=\"document.location='session_edit.php?ss=${'session_start_' . $i}&se=${'session_end_' . $i}';\">
<td>" . ${'session_start_' . $i} . "-" . ${'session_end_' . $i} . "</td>
</tr>";
echo "</table>";
}
}
}
?>
I think you are on wrong way. The things like this is simple when you choice the some order criteria and implement it into your table - for example the time of last edit or creation of the row. After that, when you have a page length and number of the page you have to use OFFSET / LIMIT clauses for SELECT, ordered by criteria - in this way you let the MySQL engine generate the proper pages.
I have got a solution.
If you are also facing such kind of problem and want to proceed with variables only (like me):
suppose you need to show 6 results on one page and your auto_increment (suppose a column named id is the auto_increment one, in your table) values are't regular, then what you can do is, get id of the 6th element by
I am supposing that you have already connected to phpmyadmin and selected a database
$no_of_results_per_page = 6;
if(isset($_GET['page_no'])) {
$page_no = $_GET['page_no'];
} else{
$page_no = 1;
}
$upper_limit = ($page_no - 1)*$no_of_result_per_page - 1;
if($page_no > 1){
$mysql_getting_id_le = mysql_query("SELECT id FROM table LIMIT $upper_limit, 1");
while($getting_id_last_elem = mysql_fetch_array($mysql_getting_id_le)) {
$id_last_element = $getting_id_last_elem['id'];
}
} else {
$mysql_getting_id_le = mysql_query("SELECT id FROM table LIMIT 0, 1");
while($getting_id_last_elem_p_1 = mysql_fetch_array($mysql_getting_id_le)) {
$id_last_element = $getting_id_last_elem_p_1['id'];
$id_last_element = $id_last_element - 1;
}
}
The above query will help us in getting id of the last element of the page
Now we will be creating the buttons to navigate from one page to another.
$final_mysql_query = mysql_query("SELECT * FROM table WHERE id > '%id_last_element%' LIMIT $no_of_results_per_page");
//Now, we can get all data limited to show no. of results you have defined per page using a loop
$total_results = mysql_query("SELECT * FROM table");
$total_results_count = mysql_num_rows($total_results);
$total_pages = ceil($total_results_count/$no_of_results_per_page);
$page_no = '';
for($i = 1; $i <= $total_pages; $i++) {
$page_no .= "<a href='?page_no=" . $i . "'>" . $i . "</a>";
}

Accessing MySQL field values from mysql_fetch_array

I have written a calendar implementation, which is working, but displays only one set of data, I'm trying to make it appear all of the data in my select query:
$events = '';
$query = mysql_query('SELECT event_id, event_type, time, date, location, home_or_away, team_id FROM event WHERE date = "'.$deets.'"');
$num_rows = mysql_num_rows($query);
if($num_rows > 0) {
$events .= '<div id="eventsControl"><button onMouseDown="overlay()">Close</button><br /><br /><b> ' . $deets . '</b><br /><br /></div>';
while($row = mysql_fetch_array($query)){
I know it has to do with something with this, but I don't know exactly what code to imply to get 'event_type', 'time' and etc
$desc = $row['event_id'] ;
$events .= '<div id="eventsBody">' . $desc . '<br /> <hr><br /></div>';
}
}
echo $events;
?>
You can use your columns as keys in the array. So to have time, use $row['time'] and so on.
For showing multiple data, try concatenating
$desc = $row['time'] .$row['event_type']
You mean something like
$time = $row['time']
etc?
I'm not sure I've got your point
not sure what you are trying to do but if you are trying to display all columns, you can use a foreach loop
while($row = mysql_fetch_array($query)){
foreach($row as $key=>$value)
{
echo("<b>$key</b>$value<br/>");
}
}

How to make php output a link?

The following code nicely outputs the column of users i have in a mysql database table in the browser.
<?php
$len = count($name);
for($i=0;$i<$len;$i++){
echo $name[$i];
echo "<p/>";
}
?>
However i would like each name to serve as a link to an external website. The website corresponding to each $name[] in the array is on the same row in the same table. So let us say that $name[0] has website w[0].
How on earth would i go about outputting the php in the browser so that each name linked to the corresponding website? Many thanks in advance. I hope i have been clear enough. Cheers
Sorry, i should probably add the above that appears in my php script:
$name = array();
$w = array();
$i=0;
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['username'];
$w[$i] = $result['website'];
$i++;
}
while($result = mysql_fetch_array($hof)){
echo ''.$result['username'].'<br>';
}
<?php
$len = count($name);
echo '<p>'
for($i=0;$i<$len;$i++){
echo '' . $name[$i] . '';
}
echo "<p/>";
?>
However, you should start learning some HTML basics before asking questions here.
Let's go!
Step #1.
Mysql Users table exmaple:
ID | Username | Website
1 | user_1 | user-1.com
2 | user_2 | user-2.com
3 | user-3 | user-3.com
Step #2
PHP
$mysqli = new mysqli("mhost", "muser", "mpassword", "databse");
if (! mysqli_connect_errno()) {
$query = "SELECT Username,Website FROM Users ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row()) {
echo '' . $row[1] . '';
}
$result->close();
}
Easy just use ' instead of " in echo or string variable. Just like
<?php
echo ' Power Point Website';
?>

Categories