How to display data twice from a mysql table in php - php

Im making a page that will display top ten voters in a table and show the number one voter aswell. I got the top ten table to work but I can't figure out how to get the second part to work. What would I do to get it to work where it would show the top voter in a img tag like this example
img src="https://minotar.net/avatar/TOPVOTERHERE"
First part
<div class="col-md-6">
<table class="table table-striped">
<tr>
<td><strong>Username</strong></td>
<td><strong>Votes</strong></td>
</tr>
<?php
$username2 = "exampleuser";
$password2 = "pass";
$hostname = "127.0.0.1";
$dbhandle = mysql_connect($hostname, $username2 , $password2)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("mc711",$dbhandle)
or die("Could not select database");
$result = mysql_query("SELECT * FROM GALTotals ORDER BY votes DESC");
$count = 0;
while ($row = mysql_fetch_assoc($result)) {
$count++;
if($count>10){
}else{
echo "<tr>";
echo "<td>".$row['IGN']."</td>";
echo "<td>".$row['votes']."</td>";
echo "</tr>";
}
}
?>
</table>
</div>
Second Part - This is the part I dont know how to do
<div class="col-md-6">
<center>
<img src="https://minotar.net/avatar/TOPVOTERHERE">
</center>
</div>

The simplest way to do it would be to create a variable to store the top voter data before you start your while loop. Then, in the while loop, you can set this variable if you're in the first iteration.
First part:
$result = mysql_query("SELECT * FROM GALTotals ORDER BY votes DESC");
$count = 0;
$topVoterIGN = NULL;
while ($row = mysql_fetch_assoc($result)) {
$count++;
if($count>10){
}else{
echo "<tr>";
echo "<td>".$row['IGN']."</td>";
echo "<td>".$row['votes']."</td>";
echo "</tr>";
if(is_null($topVoterIGN)) {
$topVoterIGN = $row['IGN'];
}
}
}
Second Part:
<div class="col-md-6">
<center>
<img src="https://minotar.net/avatar/<?php echo $topVoterIGN; ?>">
</center>
</div>
Alternatively, you can store the top 10 voters in an array and then retrieve the first item later.

Related

How to retrieve/display multi columns single row from database to different html tags

OK so what I'm am trying to do is retrieve multiple columns of data from a single row in mysql database and basically place the data of the different columns into multiple places on my html code such as in "p" and "td" tags to display on webpage.
I have successfully been able to display the "description"(description is the name of 1 of the database columns) inside the "p" tags using PHP but I don't know how to display any other columns of the database into other html tags such as the "td" tags. There is probably going to be a total of roughly 10 columns of text in database I want to display in the webpage but again where it's displaying is in various html tags and not a table which is what I keep finding when researching and tired of banging my head on the desk. There is a small example below. I'm learning as I go so any help would be great. Thank you!
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
?>
<div class="description">
<h3>Descrption</h3>
<p>
<?php
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['Description'];
}
}
?>
</p>
</div>
<td>
<?php
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row["Material"];
}
}
?>
</td>
Try this
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="description">
<h3>Descrption</h3>
<p>
<?php
echo $row['Description'];
?>
</p>
</div>
<td>
<?php
echo $row["Material"];
?>
</td>
<?php
}
}
?>
My preference is to fetch all rows first, rather then fetching rows while rendering html, otherwise if there is an error fetching rows, it becomes mixed in with your html
I also recommend using htmlentities() to escape any html data (assuming that description or material does not already include valid html
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
?>
<div class="description">
<h3>Descrption</h3>
<p>
<?php
foreach ($rows as $row) {
echo htmlentities($row['Description']);
}
?>
</p>
</div>
<td>
<?php
foreach ($rows as $row) {
echo htmlentities($row["Material"]);
}
?>
</td>

Embedded html within while-loop to display result based on what data is returned

Hi Friends
The code I've presented displays data (moduleID & moduleName) associated with a log in user. Presently it shows specific html code associated with a moduleID that should be displayed on the screen when the user logs in. I want to implement a way to iterate through the values (Possibly if-else statement within loop) in order the specific html code i have presented to be shown when a user has one or many moduleID's attached to them.
Here is my homepageDemo.php
<?php
session_start();
//including the database connection file
include 'config.php';
$cuserID= $_SESSION['userID'];
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT m.moduleID, m.moduleName
FROM modules m
JOIN courses c ON m.courseID = c.courseID
JOIN usersDemo u ON c.courseID = u.courseID
WHERE userID = '$cuserID'"); // using mysqli_query instead
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "
<div id='loader-wrapper'>
<div id='loader'><div id='loader1'>
</div>
</div>
<p><a onclick='IS4439Function()'>IS4437</a></p>
</div>
";
}
?>
Here is the html code attached to the moduleID of IS4437
<div id="loader-wrapper">
<div id="loader"><div id="loader1">
</div>
</div>
<p><a onclick="IS4439Function()">IS4437</a></p>
</div>
Here is the html code attached to the moduleID of IS4408
<div id="loader-wrapper1">
<div id="loader"><div id="loader1">
</div>
</div>
<p><a onclick="IS4408Function()">IS4408</a></p>
</div>
EDIT
So as I've mentioned the problem i'm currently having, these are the different methods I've already tried.
Originally before embedding the html into the while loop in the homepageDemo.PHP, I simply returned the moduleID & moduleName associated with logged in user as text
<?php
session_start();
//including the database connection file
include 'config.php';
$cuserID= $_SESSION['userID'];
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT m.moduleID, m.moduleName
FROM modules m
JOIN courses c ON m.courseID = c.courseID
JOIN usersDemo u ON c.courseID = u.courseID
WHERE userID = '$cuserID'"); // using mysqli_query instead
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>"."<a>".$res['moduleID']."</a>"."</td>";
echo "<td>"."<a>".$res['moduleName']."</a>"."</td>";
}
?>
Then I attempted to iterate through the values to return the html code associated with each individual moduleID
SWITCH STATEMENT ATTEMPT:
while($res = mysqli_fetch_array($result)) {
switch ($cuserID) {
case 1:
echo "
<div id='loader-wrapper'>
<div id='loader'><div id='loader1'>
</div>
</div>
<p><a onclick='IS4439Function()'>IS4437</a></p>
</div>
";
break;
case 2:
echo "
<div id='loader-wrapper'>
<div id='loader'><div id='loader1'>
</div>
</div>
<p><a onclick='IS4408Function()'>IS4408</a></p>
</div>
";
break;
case 7:
echo"
<div id='loader-wrapper'>
Functions called
function IS4439Function() {
{
window.location.href = "global.php";
}
}
function IS4408Function() {
{
window.location.href = "isStrategy.php";
}
}
function IS4449Function() {
{
window.location.href = "webApp.php";
}
}
Unfortunately neither were what I was trying to achieve. Any thoughts?
You're really close, and I'm not exactly sure where the disconnect is, but here you go. You need to replace the hardcoded moduleID value (IS4439) with the value that you've already pull from the db. Putting together what you already have, it really just comes down to concatenation.
while($res = mysqli_fetch_array($result)) {
echo "
<div id='loader-wrapper'>
<div id='loader'><div id='loader1'>
</div>
</div>
<p><a onclick='" . $res['moduleID'] . "Function()'>". $res['moduleID'] . "</a></p>
</div>
";
}
I would suggest though, that instead of calling different functions, you consider calling just one function, and passing in the moduleID as a parameter and then act accordingly within the function.
Based on your update, you would then have this...
while($res = mysqli_fetch_array($result)) {
?>
<div id='loader-wrapper'>
<div id='loader'><div id='loader1'>
</div>
</div>
<p><a onclick='redirectFunction("<?php echo $res['moduleID']; ?>");'><?php echo $res['moduleID']; ?></a></p>
</div>
<?php
}
?>
and your function would be...
function redirectFunction(moduleID)
{
var newLocation = "";
if(moduleID == "IS4439")
{
newLocation = "global.php";
}
else if(moduleID == "IS4408")
{
newLocation = "isStrategy.php";
}
else if(moduleID == "IS4449")
{
newLocation = "webApp.php";
}
window.location.href = newLocation;
}

this is my php code to view multiple images from database.but i can only see one image in front end.please help me

<?php
$servername = "*****";
$username = "****";
$password = "";
$dbname = "****";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$product_id = intval($_GET['product_id']);
// make sure its only an id (SQL Incjection problems)
$sql = "SELECT * FROM product_gallery WHERE pid=$product_id";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
while ($row = mysqli_fetch_array($result)) {
echo"<div class='tg-productbox'>";
echo" <div id='tg-thumblider' class='tg-thumblider tg-productgalleryslider owl-carousel'>";
echo" <figure class='item'><img src='$row[product_image]' alt='image description'></figure>";
echo" </div>";
echo" </div>";
echo" </div>";
};
} else {
echo "0 results";
}
$conn->close();
?>
This is my php code to view multiple images from database.but I can only see one image in front end.please help me..there is a main image and a slider to view to multiple images. It is similar to how we see product images in a shopping site
this is my php code to view multiple images from database.but i can only see one image in front end.please help me..there is a main image and a slider to view to multiple images.its is similar to how we see product images in a shopping site
There are some other mistakes like one extra closing div in loop and semicolon }; which not necessary.
Try something like below if you are getting multiple records it will definitely work.
while ($row = mysqli_fetch_array($result)) {
extract($row);
?>
<div class='tg-productbox'>
<div id='tg-thumblider' class='tg-thumblider tg-productgalleryslider owl-carousel'>
<figure class='item'>
<img src="<?php echo $product_image; ?>" alt="image description">
</figure>
</div>
</div>
<?php
}
Changes
Remove id='tg-thumblider' from echo "<div id='tg-thumblider' class='tg-thumblider. ID must need to be unique. According to the code provided, In while loop, every <div> will have same ID, which is wrong. So, either remove that ID or give some unique ID to each div.
Remove extra echo "</div>";
Remove ; from closing of while loop.
Code:
<?php
if ($result->num_rows > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<div class='tg-productbox'>";
echo "<div class='tg-thumblider tg-productgalleryslider owl-carousel'>";
echo "<figure class='item'><img src='".$row['product_image']."' alt='image description'></figure>";
echo "</div>";
echo "</div>";
}
}?>

Can't print certain values from database in PHP

I'm using this database and I have created a table in my PHP file where I list all of these values. I have link my "subject" values to a different file which is supposed to display "description", but every time when I click on "Subject" I get the description from the first input in the table.
This is my code for displaying the table
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
require_once("models/header.php");
?>
<?php
ob_start();
include 'organize_meeting.php';
ob_end_clean();
$mysqli = new mysqli("localhost", "root", "", "users");
$curr_user = $loggedInUser->username;
mysql_connect('localhost', 'root', '');
mysql_select_db('users');
$query = "SELECT * FROM uc_messages WHERE `to` = '$curr_user'";
$records = mysql_query($query);
echo "
<body>
<div id='wrapper'>
<div id='top'><div id='logo'></div></div>
<div id='content'>
<h2>My Meetings</h2>
<div id='left-nav'>";
include("left-nav.php");
echo "
</div>
<div id='main'>
</div>
<div id='bottom'></div>
</div>
</body>
</html>";
?>
<table width = "600" border = "1" cellpadding = "1" cellspacing = "1">
<tr>
<th>From</th>
<th>Subject</th>
<th>Beginning of meeting</th>
<th>End of meeting</th>
</tr>
<?php
while($msgs = mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>".$msgs['from']."</td>";
echo "
<td>
<a href = 'info.php' target = '_blank_'> ".$msgs['subject']." </a>
</td>
</html>";
echo "<td>".$msgs['TimeFrom']."</td>";
echo "<td>".$msgs['TimeTo']."</td>";
echo "<tr>";
}
?>
And this is my code that is suppoused to display the description
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
require_once("models/header.php");
?>
<?php
ob_start();
include 'organize_meeting.php';
ob_end_clean();
$mysqli = new mysqli("localhost", "root", "", "users");
$curr_user = $loggedInUser->username;
mysql_connect('localhost', 'root', '');
mysql_select_db('users');
$query = "SELECT * FROM uc_messages WHERE `to` = '$curr_user'";
$records = mysql_query($query);
echo "
<body>
<div id='wrapper'>
<div id='top'><div id='logo'></div></div>
<div id='content'>
<h2>About Meeting</h2>
<div id='left-nav'>";
echo "
</div>
<div id='main'>
</div>
<div id='bottom'></div>
</div>
</body>
</html>";
?>
<?php
$msgs = mysql_fetch_assoc($records);
echo "<p>".$msgs['from']."</p>";
echo "<p>".$msgs['description']."</p>";
echo "<p>".$msgs['TimeFrom']."</p>";
echo "<p>".$msgs['TimeTo']."</p>";
?>
I always get the same description from the database, although I click on a different input.
Note: You are mixing up mysqli.* and the mysql together and you have to convert to mysqli.* the entire query that you have. You have to fix all the mix up codes that you have and after that you follow the code that i have given.
And the below example i am giving in the statement of the mysqli.* and you have to make changes to the code.
File One:
You are missing to pass the ID of the subject or the auto increment ID in the <a> tag which you want to display.
Hence the following <a> tag will be as follows.
Replace:
<td>
<a href = 'info.php' target = '_blank_'> ".$msgs['subject']." </a>
</td>
With:
<td>
<a href = 'info.php?subject_id=".$msgs['id']."' target = '_blank_'> ".$msgs['subject']." </a>
</td>
File Two:
Hence you can get the Request that we have passed in the <a> tag over here and we shall manipulate it.
$msgs = mysqli_fetch_assoc($records)
echo "<p>".$msgs['from']."</p>";
echo "<p>".$msgs['description']."</p>";
echo "<p>".$msgs['TimeFrom']."</p>";
echo "<p>".$msgs['TimeTo']."</p>";
Remove these lines since it makes no sense. Already you have connected to the DB using the mysqli connectivity.
mysql_connect('localhost', 'root', '');
mysql_select_db('users');
Change the query like this so that it will be the mysqli.* way.
$query = "SELECT * FROM uc_messages WHERE `id` = '".$_REQUEST['subject_id']."'";
$records = mysqli_query($mysqli,$query);

How to get multiple records to display in webpage on mysql query?

I know this is a stupid question, and I've tried looking at the other answers, but they are not working for me. I have taken over maintaining a site with a lot of pre-existent code, and need to add in a new query.
I have managed to get the query to work and to display in the webpage, but only the first record displays. I know somehow I'm missing the looping function, but I can't figure out how to add it to the function so all records display.
I've been fighting with this for hours, and would really appreciate some pointers!
Here's the code in the main listing.php file - the first query is pre-existing, the new query is to the getFeedback procedure starts with "$sql2 = "CALL sp_GetFeedback(".$listing['unique_listing_id'].")";".
if(($PMDR->get('Authentication')->checkPermission('admin_view_real_prices')) || ($PMDR->get('Session')->get('user_id'))) {
$admin_user_can_view_prices = true;
$template_content->set('admin_user_can_view_prices',$admin_user_can_view_prices);
$sql = "CALL sp_Entertainers_Contact_Info(".$listing['unique_listing_id'].")";
//all variables come from db.php
$mysqli = new mysqli($dbserver, $dbuser, $dbpass, $dbnameaf);
$rs = $mysqli->query($sql);
while($row = $rs->fetch_assoc())
{
$template_content->set('primaryEmail',$row['PrimaryEmail']);
$template_content->set('secondaryEmail',$row['SecondaryEmail']);
$template_content->set('cellPhone',$row['CellPhone']);
$template_content->set('homePhone',$row['HomePhone']);
$template_content->set('alternatePhone',$row['AlternatePhone (Please Specify)']);
$template_content->set('streetAddress',$row['StreetAddress']);
$template_content->set('entertainerCity',$row['City']);
$template_content->set('entertainerState',$row['State']);
$template_content->set('entertainerZip',$row['Zip']);
$template_content->set('entertainerNotes',$row['Note']);
}
$data = "";
$griddata = "";
$grid = "";
$entertainerid = $_POST['unique_listing_id'];
$mysqli = new mysqli($dbserver, $dbuser, $dbpass, $dbnameaf);
$sql2 = "CALL sp_GetFeedback(".$listing['unique_listing_id'].")";
$rs = $mysqli->query($sql2);
$numrows = mysqli_num_rows($rs)." Rows";
while($row = $rs->fetch_assoc()) {
$allRows[] = $row;
$style = ($altRowCount % 2 == 0 ? ' class="row" ' : ' class="row tdg" ');
$template_content->set('eventID',$row['EventID']);
$template_content->set('dateOfEvent',$row['DateOfEvent']);
$template_content->set('clientFollow',$row['ClientFollowUp']);
$template_content->set('performerFollow',$row['PerformerFollowUp']);
$griddata .= "
<div $style>
<div class='col-xs-2 col-sm-2 col-md-2' onclick=\"popupEvent('".$row['EventID']."')\">".$eventID."</div>
<div class='col-xs-2 col-sm-2 col-md-2'>".$dateOfEvent."</div>
<div class='col-xs-4 col-sm-4 col-md-4'>".$clientFollow."</div>
<div class='col-xs-4 col-sm-4 col-md-4'>".$performerFollow."</div>
</div>
";
$altRowCount = $altRowCount + 1;
}
$mysqli->close();
$grid = "
<div style='max-height: 110px; overflow: scroll;'>
<table class='fancygrid'>
<tbody>
".$griddata."
</tbody>
</table>
</div>
<!-- <div style='width: 100%; font-weight: bold; color: red;'>".$numrows."</div> -->
";
echo $gridHeader.$grid;
} //getEntertainerFeedback
} // is an office user logged in? -- end
Here's the code that is in the included listing.tpl file that contains the HTML for the webpage:
<div class="row">
<div class='col-xs-2 col-sm-2 col-md-2' onclick="popupEvent(".$row['eventID'].")"><?php echo $eventID ?></div>
<div class='col-xs-2 col-sm-2 col-md-2'><?php echo $dateOfEvent ?></div>
<div class='col-xs-4 col-sm-4 col-md-4'><?php echo $clientFollow ?></div>
<div class='col-xs-4 col-sm-4 col-md-4'><?php echo $performerFollow ?></div>
</div>
I tried adding
<?php
foreach ($allRows as $row) {
?>
<?php } ?>
around the html code above but that just causes no records to display at all, not even one.
Since you have to be logged in to view this data, I can't share the link, but here's what the blue logged in area looks like with the one record showing at bottom of blue box:
ETA: FYI - I also tried just echoing .grid in my html code - but that gives me not results at all, not sure why.
Any help to point me in the right direction or tell me what I'm missing is greatly appreciated!!
Thanks!
First of all, you have opened database connection twice
$data = "";
$griddata = "";
$grid = "";
$entertainerid = $_POST['unique_listing_id'];
# remove this line, just to be sure it doesn't cause any problems
$mysqli = new mysqli($dbserver, $dbuser, $dbpass, $dbnameaf);
$sql2 = "CALL sp_GetFeedback(".$listing['unique_listing_id'].")";
Secondly, debug your query result by printing something in while loop, just to be sure that query returns multiple rows as result
And last thing I should try is to declare $allRows as an Array before your while loop, just for safety
$allRows = array();
while($row = $rs->fetch_assoc()) {
$allRows[] = $row;
Then try this approach
<?php
foreach ($allRows as $row) {
?>
<!-- HTML -->
<?php } ?>
Edit:
This looks like some kind of View object, so you have predefined HTML code in it and you just fill it with your values from database, so I think your while statement is overriding values in your view with each loop and that's the reason why you probably get one record. Your View is probably designed to hold one row/data
$template_content->set('eventID',$row['EventID']);
$template_content->set('dateOfEvent',$row['DateOfEvent']);
$template_content->set('clientFollow',$row['ClientFollowUp']);
$template_content->set('performerFollow',$row['PerformerFollowUp']);

Categories