Assign div colour based on MySQL output - php

Didn't know how to word the title sorry. Basically I have a comments system, it works really simply, selects the uid of the post from a DB, then just outputs the comments tied to that UID from another DB.
The nature of the comments system is that every poster is anonymous, because of that, it's hard to track whether you're communicating with the same person or not, for that reason, I want to make the div wrapped around the comment be a specific colour, and for each comment by that person on that post to be that colour. The only thing that ties a users comments together is the IP address.
My code thus far:
$sql = "SELECT * FROM anonpost_com WHERE uid = '$uid' ORDER BY date DESC";
$result = mysql_query($sql) or print ("Can't select entry from table anonpost.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$date = date("l F d Y", strtotime($row['date']));
$comment = stripslashes($row['comment']);
$uid = ($row['uid']);
$cid = ($row['cid']);
$ip = ($row['ip']);
?>
<div id="comments" style="border:1px solid <?php echo $colour; ?>;">
<p><?php echo $comment; ?></p>
<h4>by <i>Anonymous</i> on <?php echo $date; ?></h4>
</div>
<?php
}
?>
$colour comes from:
$colour = dechex(rand(0,10000000);
But I'm unsure how to make $colour the same for every instance of the same IP on a comment...
Any help would be appreciated!

I would agree that IP address might not be the best solution, but to do that:
$sql = "SELECT * FROM anonpost_com WHERE uid = '$uid' ORDER BY date DESC";
$colours = array();
$result = mysql_query($sql) or print ("Can't select entry from table anonpost.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$date = date("l F d Y", strtotime($row['date']));
$comment = stripslashes($row['comment']);
$uid = ($row['uid']);
$cid = ($row['cid']);
$ip = ($row['ip']);
if (!isset($colours[$ip])) {
$colours[$ip] = dechex(rand(0,10000000);
}
$colour = $colours[$ip];
?>
<div id="comments" style="border:1px solid <?php echo $colour; ?>;">
<p><?php echo $comment; ?></p>
<h4>by <i>Anonymous</i> on <?php echo $date; ?></h4>
</div>
<?php
}
?>
Note that the colour will change each time the page loads.

Related

How to echo all rows with certain aspect

I have two tables. They are connected via a one (userinfo) to many (achievements) foreign key relationship. What I am attempting to do below is echo all the rows which have the given $usrid. This could be more than one.
Unfortunately, It only echos content one of the rows. How can I change it to echo all the rows where a a certain userid is present?
<!DOCTYPE HTML>
<head>
<?php $usrid = $_GET['usrid'];
$connection = #mysqli_connect("localhost","root","","Rain")
OR die('Could not connect' .
mysqli_connect_error());
$query = "SELECT usrid, username, oldname, languages, joindate, art, hunting, frontwebdev, backwebdev, writing, programming, se, smm, pentesting, timezone, availability, reliability, profilePicture FROM userinfo WHERE usrid='" . $usrid . "';";
$response = #mysqli_query($connection,$query);
$row = #mysqli_fetch_array($response);
$username = $row['username'];
$achvquery = "SELECT achieveid, usrid, achievementname, achievementdescr, timestamp FROM achievements WHERE usrid=" . $usrid . ";";
$achvresponse = #mysqli_query($connection,$achvquery);
$achvrow = #mysqli_fetch_array($achvresponse);
$achvtitle = $achvrow['achievementname'];
$achvdescr = $achvrow['achievementdescr'];
?>
<title>
All Achievements
</title>
</head>
<body>
<span> <?php echo "<span> " . $username . "s OD Achievement History "; ?> </span>
<span id="newAchvLink"> <?php echo "<a id='addNewLink' href='addachievement.php?usrid=" . $usrid . "'> Add new</a>"; ?></span>
<br /> <?php echo "<h2> Achv: </h2> <h3 class='achvtitle'>" . $achvtitle . "</h3>"; echo $achvdescr;?><br /><br />
</body>
</html>
You can use while loop to print all row
$query = "SELECT usrid, username, oldname, languages, joindate, art, hunting, frontwebdev, backwebdev, writing, programming, se, smm, pentesting, timezone,
availability, reliability, profilePicture FROM userinfo WHERE usrid='" . $usrid . "';";
$response = #mysqli_query($connection,$query);
while ($row = #mysqli_fetch_array($response))
{
echo $row['username'];
}
Where you have the PHP echo statement you can replace it with something like...
while($row = $result->fetch_assoc($response)) {
echo "<span> " . $username . "s Op Achievement History ";
You should look at JOIN to simplify all of this for you.
https://www.w3schools.com/sql/sql_join.asp
This is a pretty good/easy to understand usage of PHP Loops.
https://www.tutorialspoint.com/php/php_loop_types.htm
first table query
while loop
{
$userid=first_table_data['user_id'];
2nd table query where userid=$userid
while loop
{
}
all value save in array
}
print value

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

MySQL link to return results

I have an image that is displayed from a table and I want the user to be able to click the image which directs them to a page that returns the rest of the data for that row. Do I need a php loop for this? I can't quite figure it out.
This returns the Last Name, First Name, and an Image:
<?php
if (isset($_GET['LastName'])) {
$ln = $_GET['LastName'];
}
include 'connection.php';
$query = "SELECT * FROM residents WHERE LastName like '$ln%' ";
$result = mysql_query($query);
while($person = mysql_fetch_array($result)) { ?>
<div class="media col-sm-4">
<a class="pull-left" href="redirectionpage.php?<?php echo $person['ID'];?>.php">
<img class="media-object" src="upload/<?php echo $person['Picture'];?>" width="100" height="100"/>
</a>
<div class="media-body">
<h4 class="media-heading"><?php echo $person['LastName'] . ", " . $person['FirstName']; ?></h4>
</div>
</div>
<?php }>?
Is the best way to accomplish this by redirecting the user to a new page and using a mysql statement to display the new data?
This is the code for the other page:
<?php
//Gets data from the database
include ('header.php');
include ('footer.php');
include ('connection.php');
$query = "SELECT * FROM residents WHERE ID = LastName LIMIT 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$outputpicture.='<div><p><img src="upload/' . $row['Picture'].'" width="450" height="550"/></p></div>';
$outputname.= $row['LastName'] . ", " . $row['FirstName']. '<br />';
$outputspouse.= $row['Spouse']. '<br />';
$outputrelatives.= $row['Relatives']. '<br />';
$outputaddress.= $row['Address']. '<br />';
$outputbirthday.= $row['Birthday']. '<br />';
$outputbegan.= $row['BeganResidence']. '<br />';
$outputended.= $row['EndedResidence']. '<br />';
$outputformer.= $row['FormerResidence']. '<br />';
$outputcareer.= $row['Career']. '<br />';
$outputeducation.= $row['Education']. '<br />';
$outputmaritalstatus.= $row['MaritalStatus']. '<br />';
$outputsiblings.= $row['Siblings']. '<br />';
$outputspecialinterests.= $row['SpecialInterests'].'<br />';
}
?>
The link needs to be changed to
<a class="pull-left" href="redirectionpage.php?id=<?php echo $person['ID'];?>">
Adding this id= will allow you to access the id parameter in redirectionpage.php via the $_GET superglobal.
$id = $_GET['id'];
You can use the $id variable to select the specified row from your database. You will see a lot of examples that do it like this:
$query = "SELECT * FROM residents WHERE ID = $id";
This works but you should not do it, because it creates an SQL injection vulnerability. Read about prepared statements and create your SQL so that you can pass the ID as a paramater.
$stmt = $pdo->prepare("SELECT * FROM residents WHERE ID = :id");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
This should also be applied to the code you use to select the list of images.
Assuming ID is the key for your residents table, this should select only one record, so you will not need the while loop. You can just use one fetch.

Echo array based on distinct key

I have “ordered by” a database to be in ascending country order, then descending years. Each database record contains: countryname, year, details. There are many duplicate countries, but the years are different. For instance:
Albania, 2000, details
Albania, 1965, details
Croatia, 2014, details
Croatia, 2003, details
Can’t figure out how to echo the array to get results like the following where country is on one line and years & details are listed below without duplicating the name of the country:
Albania
2000, details
1965, details
Croatia
2014, details
2003, details
Seems like I need foreach distinct country, echo year and details?
Here is my php so far:
$result = mysql_query("SELECT country, year, details FROM studies ORDER BY country, year DESC ");
//output data from each row in db
while($row = mysql_fetch_array($result)) {
echo " Country: " .$row['country']. "<br /> Year: " .$row['year']. " Details: ".$row['details']. "<br /><br /> ";
}
Would appreciate any help, I'm stumped!
Try adding a country check:
$newcountry = '';
while($row = mysql_fetch_array($result)) {
if ($newcountry != $row['country']) {
echo "Country:". $row['country']."<br />";
$newcountry = $row['country'];
}
echo " Year: " .$row['year']. " Details: ".$row['details']. "<br /><br /> ";
}
This should work, because you have ordered your query by Country. This is critical, otherwise you should absolutely add a GROUP BY clause to your SQL.
EDIT: to add a <div> around the group, you simply would change the echo sequence, checking first to see if the country has already been set once. It would look like:
$newcountry = 'undefined';
while($row = mysql_fetch_array($result)) {
if ($newcountry !='undefined' && $newcountry != $row['country']){
echo '</div>'; // only add a closing div if a new country (and not 1st)
}
if ($newcountry != $row['country']) {
echo "Country:". $row['country']."<br /><div class='countryDetail'>";
$newcountry = $row['country'];
}// added the start of the <div>
echo " Year: " .$row['year']. " Details: ".$row['details']. "<br /><br /> ";
}
if ($newcountry != 'undefined') { //make sure at least one <div> is set
echo "</div>"; // close the last <div>
}
I added the class countryDetail to the div, so you can use this with toggle in your jQuery.
You can use nested while loops. You might also want to use PDO/mysqli_ functions/prepared statements in place of mysql_ functions:
// get unique country list first
$sql1 = "SELECT DISTINCT(country) FROM studies ORDER BY country";
$result1 = mysql_query($sql1);
// iterate through result set of sql1
while($row1 = mysql_fetch_array($result1))
{
$country = $row1['country'];
echo "<br>"; // new line
echo $country;
// get year, details for each country
$sql2 = "SELECT year, details FROM studies WHERE country = '$country' ORDER BY year DESC";
$result2 = mysql_query($sql2);
// iterate through result set of $sql2
while ($row2 = mysql_fetch_array($result2))
{
echo "<br>"; // new line
echo $row2['year']. ", " . $row2['details'];
}
}
loop party!
$rows = [];
while($row = mysql_fetch_array($result)) {
$rows[ $row['country'] ] = [ $row['year'], $row['details'] ];
}
foreach($rows as $country => $row) {
$details = array_map(function($items) { return sprintf("\t - %s: %s\n", $items[0], $items[1]) }, $row);
echo sprintf("\n%s:\n %s", $country, $details);
}

Efficient Method To Display Group Title Once — PHP/MySQL/jQuery

There are three tables in MySQL: Employees, Branches, Departments. I need information to appear in the following way:
ATLANTA Branch Delivery Department Phillip J. Fry Phone: 123456
Engineering Department Turanga Leela Phone: 123457
Bender Rodriguez Phone: 123458
The simple PHP code currently:
1) Takes rows from three tables (simple SELECT query with JOIN)
2) Puts them in row (mysql_fetch_assoc)
3) Displays using the PHP While loop
The result is then like this:
ATLANTA Branch Delivery Department Phillip J. Fry Phone: 123456
ATLANTA Branch Engineering Department Turanga Leela Phone: 123457
ATLANTA Branch Engineering Department Bender Rodriguez Phone: 123458
What technique (JS, jQuery, Ajax) or method can you recommend so I can pull row information using only one query and not duplicate the Branch name and Department name?
UPDATE: If I put the branch name outside the loop (using While loop), there would be multiple loops: 1) To get a branch, 2) To get a department, 3) To get all employees in that department. Loop.
UPDATE: Sharing the code:
<?php
// Create connection
$connection = mysql_connect('localhost','root', '') or die('Connection error.');
mysql_query("SET NAMES 'utf8'", $connection);
mysql_select_db("eReference");
// Check Employees
$query = "SELECT Employees.fName, Employees.lName, Department.deptName, Branch.branchName, ".
"FROM Employees ".
"LEFT JOIN Department ".
"ON Employees.department = Department.id ".
"LEFT JOIN Branch ".
"ON Employees.branch = Branch.id ;";
$result = mysql_query($query, $connection) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
?>
<h2><?php echo $row['branchName']; ?></h2>
<?php if ($row['deptName']) echo "<h3>" . $row['deptName'] . "</h3>"; ?>
<h4><?php echo $row['fName'] . " " . $row['lName']; ?></h4></p>
<?php
}
?>
<?php
$i = 1; // to be incremented after printing branchName once
while ($row = mysql_fetch_assoc($result)) {
if($i == 1) { ?>
<h2><?php echo $row['branchName']; $i ++; ?></h2>
<?php } ?>
<?php if ($row['deptName']) echo "<h3>" . $row['deptName'] . "</h3>"; ?>
<h4><?php echo $row['fName'] . " " . $row['lName']; ?></h4></p>
<?php } ?>
Just add a variable $i = 1 and check before printing if it is equal to 1. After printing it for first time, increment it.
It is just addition of an if statement.
Hope this helps.
This is how I would do it.
Create a multi-dimensional array with the data, and iterate through the array to render the output.
This will not be the most efficient in terms of memory usage, but unless you have thousands of rows of data, it probably won't be an issue.
The benefit of this, is that the html rendering code is much simpler and easier to understand, plus sql and html are not intermingled. (which is good for code maintenance)
<?php
// Create connection
$connection = mysql_connect('localhost','root', '') or die('Connection error.');
mysql_query("SET NAMES 'utf8'", $connection);
mysql_select_db("eReference");
// Check Employees
$query = "SELECT Employees.fName, Employees.lName, Department.deptName, Branch.branchName, ".
"FROM Employees ".
"LEFT JOIN Department ".
"ON Employees.department = Department.id ".
"LEFT JOIN Branch ".
"ON Employees.branch = Branch.id ;";
// note you probably want to add an order by statement here too, to ensure consistent sorting
$result = mysql_query($query, $connection) or die(mysql_error());
$data = array();
// build a multi-dimensional array from the result set
while ($row = mysql_fetch_assoc($result)) {
$data[($row['branchName'])][($row['deptName'])][] = array(
'name' => "{$row['fName']} {$row['lName']}",
'phone' => $row['phone'] // add phone, doesn't exist in original query, but just to illustrate how it would work
);
}
// sql finishes here
?>
<?php
// html rendering
// use htmlentities to escape any html chars, such as < > etc
foreach ($data as $branchName => $departments) {
echo '<h2>',htmlentities($branchName),'</h2>';
foreach ($departments as $deptName => $employees) {
foreach ($employees as $employee) {
echo '<h3>',htmlentities($deptName),'</h3>';
echo '<h4>',htmlentities($employee['name']),'</h4>';
echo '<h4>',htmlentities($employee['phone']),'</h4>';
}
}
}
?>
The result gotten from your sql should be an array so use a while loop to iterate throw the array while echo the result of the current index
Maybe this will work..
<?php
$deptName;
while($row = mysql_fetch_assoc($result))
{
if ($row['deptName'])
{
if ($deptName != $row['deptName'])
{
echo "<h3>" . $row['deptName'] . "</h3>";
$deptName = $row['deptName'];
}
}
}
?>
$result = mysql_query($query, $connection) or die(mysql_error());
$newarray = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$newarray[$i]['deptName'] = $row['deptName'];
$newarray[$i]['fName'] = $row['fName'];
$newarray[$i]['lName'] = $row['lName'];
$i++;
}
<h2><?php echo $newarray[0]['branchName']; ?></h2>
while($newarray){
?>
<?php if ($newarray['deptName']) echo "<h3>" . $newarray['deptName'] . "</h3>"; ?>
<h4><?php echo $newarray['fName'] . " " . $newarray['lName']; ?></h4></p>
}
?>
So, this is what it did:
$query = "SELECT Employees.lName, Employees.fName, Employees.mName, Position.position, ".
"department.deptName, department.deptId, ".
"Branch.branchName, Branch.branchId, ContactInformation.* ".
"FROM Employees ".
"LEFT JOIN Position ".
"ON Employees.position = Position.id ".
"LEFT JOIN Department ".
"ON Employees.department = Department.deptId ".
"LEFT JOIN Branch ".
"ON Employees.branch = Branch.branchId ".
"LEFT JOIN ContactInformation ".
"ON Employees.contactInformation = ContactInformation.id ".
"ORDER BY Employees.branch, Employees.department ASC;";
$result = mysql_query($query, $connection) or die(mysql_error());
$arrayOfEmployees = array();
while ($row = mysql_fetch_assoc($result)) {
$arrayOfEmployees[($row['branchName'])][($row['deptName'])][] = array(
'lName' => $row['lName'],
'fName' => $row['fName'],
'mName' => $row['mName'],
'position' => $row['position'],
'lPhone1' => $row['lPhone1'],
'lPhone2' => $row['lPhone2'],
'mPhone' => $row['mPhone'],
'fax' => $row['fax'],
'office' => $row['office'],
'email' => $row['email']
);
}
foreach($arrayOfEmployees as $branchName => $arrayOfDepartments) {
echo "<h2>".$branchName."</h2>";
foreach($arrayOfDepartments as $deptName => $arrayOfEmployeeContacts) {
echo '<h3>',htmlentities($deptName),'</h3>';
foreach($arrayOfEmployeeContacts as $employeeContacts) {
echo "<h4>".$employeeContacts["lName"]." ".$employeeContacts["fName"]." ".$employeeContacts["mName"]."</h4>";
echo "<p>";
if($employeeContacts["position"]) echo $employeeContacts["position"]."<br>";
$num = $employeeContacts["lPhone1"];
if($employeeContacts["lPhone1"]) echo "+".substr($num,0,1)." (".substr($num,1,4).") "." ".substr($num,5,2)."-".substr($num,7,2)."-".substr($num,9,2)."<br>";
$num = $employeeContacts["lPhone2"];
if($employeeContacts["lPhone2"]) echo "+".substr($num,0,1)." (".substr($num,1,4).") "." ".substr($num,5,2)."-".substr($num,7,2)."-".substr($num,9,2)."<br>";
$num = $employeeContacts["mPhone"];
if($employeeContacts["mPhone"]) echo "+".substr($num,0,1)." (".substr($num,1,3).") "." ".substr($num,4,3)."-".substr($num,7,2)."-".substr($num,9,2)."<br>";
$num = $employeeContacts["fax"];
if($employeeContacts["fax"]) echo "+".substr($num,0,1)." (".substr($num,1,4).") "." ".substr($num,5,2)."-".substr($num,7,2)."-".substr($num,9,2)."<br>";
if($employeeContacts["email"]) echo "".$employeeContacts["email"]."<br>";
if($employeeContacts["office"]) echo "Кабинет — ".$employeeContacts["office"];
echo "</p>";
}
}
}
Tested. The solution works well dynamically — just add more branches and departments into the database. Here is the efficiency check against the method I originally used (in microseconds):
Array-based Original
1 1.015 1.012
2 1.016 1.02
3 1.026 1.013
4 1.015 1.002
5 1.026 1.02
6 1.014 1.02
7 1.013 1.019
8 1.005 1.014
9 1.013 1.006
10 1.021 1.015
Average 1.0164 1.0141

Categories