PHP shows top 4 rows on different places - php

I have the following html code:
<div class="content-block1">
<div class="image-block1"></div>
<div class="bear1"></div>
<div class="where-block1"></div>
<div class="intro-block1"></div>
<div class="map-block1"></div>
<div class="extra-block1"></div>
<div class="coordinates-block1"></div>
<div class="button-block1">More...</div>
</div>
<div class="content-block2">
<div class="image-block2"></div>
<div class="bear2">/div>
<div class="where-block2"></div>
<div class="intro-block2"></div>
<div class="map-block2"></div>
<div class="extra-block2"></div>
<div class="coordinates-block2"></div>
<div class="button-block2">More...</div>
</div>
..and the following PHP code:
$host = "localhost";
$user = "username";
$pass = "password";
$database = "db";
mysql_connect($host,$user,$pass,$database) or die(mysql_error());
mysql_query("SET NAMES 'utf8'");
$query = mysql_query("select image,where,intro,map,extra,coordinates from content limit 2");
mysql_close();
Now, I've tried so hard to do following: I need to select top 2 rows in table content which include columns image,where,intro,map,extra and coordinates (bear excluded). Okay, I've selected them with query, BUT I have next problem -> I need to put content from first row in first DIV element called content-block1, so, columns image,where,intro,map,extra and coordinates need to fit in their divs in content-block1.
Also, I need to put data from second row (image,where,intro,map,extra and coordinates) into DIV element called content-block2 into DIVs where they belong. Can you help me please?

I think this could be what you are looking for...
$host = "localhost";
$user = "username";
$pass = "password";
$database = "db";
mysql_connect($host,$user,$pass,$database) or die(mysql_error());
mysql_query("SET NAMES 'utf8'");
$query = mysql_query("select image,where,intro,map,extra,coordinates from content limit 2");
$i = 0;
while($row = mysql_fetch_array($query , MYSQL_ASSOC))
{
$i++;
echo '
<div class="content-block{$i}">
<div class="image-block{$i}">{$row['yourvaluehere']}</div>
<div class="bear{$i}">{$row['yourvaluehere']}</div>
<div class="where-block{$i}">{$row['yourvaluehere']}</div>
<div class="intro-block{$i}">{$row['yourvaluehere']}</div>
<div class="map-block{$i}">{$row['yourvaluehere']}</div>
<div class="extra-block{$i}"></div>
<div class="coordinates-block{$i}">{$row['yourvaluehere']}</div>
<div class="button-block{$i}">More...</div>
</div>
';
}

Try changing your Query to this
$query = mysql_query("select * from content limit 0, 2");
Source = https://dev.mysql.com/doc/refman/5.0/en/select.html
Then do the following to get your query values
while($row = mysqli_fetch_array($query))
{
$image = $row['image'];
$where = $row['where'];
$map = $row['intro'];
$extra = $row['extra'];
$coordinates = $row['coordinates'];
}
This would be your query if you were selecting the top two only
$query = mysql_query("select TOP 2 * from content");

Related

How to select data from each row of database using php

I am working to create a Blog page, I want to retrieve data from database using php. I have created 2 pages:
Blogs Page
Preview Page
Blog page is used to retrieve all data from the database and display only Title and Concept of the blog. After the concept there is a button to view whole blog. I am uploading example of UI, like how should it look.
Blog Example
After clicking on button, it should Navigate to preview page where whole content of blog should be dynamically changed as according to Title selected in Blog Page.
Now, I've created 2 blogs on backend but it is taking all the values from database of the latest one that I created recently, even when I am clicking on the button of the blog which I created 2 days ago.
Code for Blog Page that I written is:
<?php
session_start();
$dbHost = "localhost";
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'Database';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($db->connect_error){
die("Connection failed: " . $db->connect_error);
}
$sql = $db->prepare('Select * from blogs;');
$sql->execute();
$result = $sql->get_result();
?>
<!DOCTYPE html>
<html>
<head>
<title>Blogs</title>
<?php include '_header.html'; ?>
<link rel="stylesheet" href="css/about.css">
<link rel="stylesheet" href="css/blog.css">
</head>
<body>
<?php include '_navbar.html'; ?>
<div class="bg2">
<h1>Our Opinion</h1>
</div>
<div class="col-sm-12">
<div class="container">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<?php
if($result)
{
while($row = $result->fetch_assoc())
{
echo "<h3><a href = 'preview.php' style = 'color:black'>".$row['Title']."</a></h3>";
$_SESSION['Title'] = $row['Title'];
echo "<p>".$row['concept']."</p><hr>";
}
}
?>
</div><hr>
</div>
</div>
</div>
</div>
<div style="padding:50px"></div>
<?php include '_footer1.html'; ?>
<?php include '_footer.html'; ?>
</body>
</html>
And code for Preview Page is:
<?php
session_start();
$title = $_SESSION['Title'];
$dbHost = "localhost";
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'database';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($db->connect_error){
die("Connection failed: " . $db->connect_error);
}
$sql = $db->prepare("SELECT * FROM blogs where Title = ?");
$sql ->bind_param("s",$title);
$sql->execute();
$result = $sql ->get_result();
?>
<!DOCTYPE html>
<html>
<head>
<title>Preview</title>
<?php include '_header.html'; ?>
<link rel="stylesheet" href="css/treatment.css">
</head>
<body>
<?php include '_navbar.html'; ?>
<div class="col-sm-12">
<div class="container-fluid">
<div style="text-align:center">
<img src = "img/Ayurvedjya 02.png" alt = "Ayurvedajya Logo" width = "15%">
</div>
<?php
if($result)
{
while($row = $result->fetch_assoc())
{
echo "<h3>".$row['Title']."</h3><hr>";
?>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-9">
<?php echo "<p><b>".$row['Content']."</b></p>";?>
</div>
<div class="col-sm-3">
<?php
echo '<img src="img/'.$row['image'].'" width= 100%/>';
?>
</div>
</div>
</div>
<?php }}else {echo "No Data";}?>
</div>
</div>
<div style="padding:50px"></div>
<?php include '_footer1.html'; ?>
<?php include '_footer.html'; ?>
</body>
</html>
Can anyone please confirm where I am going wrong and How can I fix this?
you're putting the data of each row into the session, overwriting that value each time it loops, and then redirecting afterwards (your header values get overwritten on each loop too, only the last one is issued to the browser). The title you're putting into the session is unrelated to what was actually clicked on. Your form needs to send the ID of the clicked blog and then use that, not the data fetched from the database.
Also for this scenario there's really no reason to post the form to the same script and then redirect (as per your original code). A simple hyperlink with a query parameter will do the job very nicely:
Blog page:
echo "<h3><a href = 'preview.php?id=".$row["ID"]."' style = 'color:black'>".$row['Title']."</a></h3>";
Preview page:
<?php
session_start();
$id = $_GET["id"]; //get the ID from the URL
//... etc, then
$sql = $db->prepare("SELECT * FROM blogs where ID = ?");
$sql ->bind_param("i",$id);
Note that I'm assuming here that your blogs have an integer ID column as the primary key in the database - this would be normal practice, and it's more robust to use that as the query parameter than the title (because titles can change, or not be unique, or have characters in them which don't work well in a URL, etc. so I strongly suggest you use the ID to identify the blog instead of the title).

PHP - check if cell is empty

I'm writing a simple PHP page that is pulling information through into cards.
At the moment my script is hard coding the amount of "linktitle_1, linktitle_2, linktitle_3" etc that are able to be pulled through, at the moment it is 3, and if any of the 3 cells are empty they are still echoed out as empty, and with a comma afterwards.
What I want to do is to be able to print out any from 0-7 items of information. (The appropriate columns are present in the database)
Psuedo code would be something like this:
if (linktitle_1 = empty, linktitle_1_url = empty) {
echo '<p>linktitle_1</p>'}
else {
do nothing
};
I'm looking to do this with both the related links, and the link title sections. So I guess what I need to know is:
How do I escape the echo that these statements are to be inside of?
How do I use an if statement to check if something is empty/null?
Is there a more efficient way of doing this?
Code =
<?php
// DB details
$hostname = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM relevant_topics";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Removing special characters from rows.
while($row = $result->fetch_assoc()) {
$title_clean = $row["title"];
$title_clean = strtolower($title_clean);
$title_clean = preg_replace('/\s*/ ', '', $title_clean);
$class_clean = $row["class"];
$class_clean = strtolower($class_clean);
$class_clean = preg_replace('/\s*/ ', '', $class_clean);
$related_clean_1 = $row["related1"] ;
$related_clean_1 = strtolower($related_clean_1);
$related_clean_1 = preg_replace('/[.,]\s*/ ', '', $related_clean_1);
$related_clean_2 = $row["related2"] ;
$related_clean_2 = strtolower($related_clean_2);
$related_clean_2 = preg_replace('/[.,]\s*/ ', '', $related_clean_2);
$related_clean_3 = $row["related3"] ;
$related_clean_3 = strtolower($related_clean_3);
$related_clean_3 = preg_replace('/[.,]\s*/ ', '', $related_clean_3);
$related_clean_4 = $row["related4"] ;
$related_clean_4 = strtolower($related_clean_4);
$related_clean_4 = preg_replace('/[.,]\s*/ ', '', $related_clean_4);
echo'
<div class="mix item '.$class_clean.'">
<h3>'.$row["title"].'</h3>
<p>'.$row["description"].'</p>
</br>
<p>Related Items:</p>
<p>
'.$row["related1"].'
'.$row["related2"].'
'.$row["related3"].'
'.$row["related4"].'
'.$row["related1"].',
'.$row["related2"].',
'.$row["related3"].', </p>
</br>
<div class="item-bottom '.$row["class"].'_counter">
See more
</div>
</div>
<div id="myModal'.$title_clean.'" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title modal-top-health">'.$row["title"].'</h3>
<br>
<p>'.$row["details"].'</p>
<br>
'.$row["linktitle_1"].',
<p>'.$row["linktitle_1_desc"].'</p>
'.$row["linktitle_2"].',
<p>'.$row["linktitle_2_desc"].'</p>
'.$row["linktitle_3"].',
<p>'.$row["linktitle_3_desc"].'</p>
</div>
</div>
</div>
</div>
';
}
} else {
echo "0 results";
}
$conn->close();
?>
Optimize with a loop, store the output in a variable:
// build list of titles
$titles = '';
for($i=1; $i<=7; ++$i) {
// check for data
if($row['linktitle_'.$i.'_url'] != null && $row['linktitle_'.$i] != null) {
// add to output
$titles .= '
'.$row['linktitle_'.$i].',
<p>'.$row['linktitle_'.$i.'_desc'].'</p>';
}
}
echo '
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title modal-top-health">'.$row["title"].'</h3>
<br>
<p>'.$row["details"].'</p>
<br>'.$titles.'
</div>';
You can then change that 7 to any number.
You can use htmlspecialchars() to escape the values if they might break the HTML.
$titles .= '
<a href="'.htmlspecialchars($row['linktitle_'.$i.'_url']).'">'.
htmlspecialchars($row['linktitle_'.$i]).', </a>
<p>'.htmlspecialchars($row['linktitle_'.$i.'_desc']).'</p>';
The same logic can be applied to the related links.
It could be optimized further at the database level by having a dedicated table for the titles:
table: relevant_topics_titles
topic_id | title_id | name | url | desc
Where topic_id is a foreign key to join with your table relevant_topics while title_id is a number between 1 and 7 (or less or more).
You could then fetch all the titles associated with your topic id and loop through them to build the list of titles.

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']);

How to display data twice from a mysql table in 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.

WHERE not working when it should be?

before I start I have looked over the answers related but I cannot figure this out
Hello, I am trying to fetch the values with just the data from formtype = 'Question1'
the value is in the database under column formtype as Question1, it is a radio option value which is one of 3 values that I use to redirect information over to one page, so I have to do this on each page to get that specific information. My question is, why is it not selecting the values that contain Question1? it doesn't grab anything at all, but if I get rid of WHERE it grabs all the information just fine(which i only wanna grab the one containing Question1). Why is this? it isnt showing any errors with SELECT so I don't know what I did wrong.
I am connected to the database
<?php $db_name = 'submissions';
$db_user = 'root';
$db_pass = '';
$db_host = 'localhost';
mysql_connect("localhost", $db_user, $db_pass) or die(mysql_error());
mysql_select_db("submissions") or die(mysql_error());
$query1 = mysql_query("SELECT actual_quote,poster,formtype FROM data WHERE formtype = 'Question1'");
$info = mysql_fetch_array($query1);
while($info = mysql_fetch_array($query1)){
echo '
<div class="wrapper">
<div class="submissions">
<div class="logo-logo"><h2>Questions.</h2>
<div class="checkboxes">'.$info['formtype'].'
</div>
</div>
<div class="top-submit">
&#8220'. $info["actual_quote"] . '”
</div>
<div class="poster">- '. $info["poster"].'
<div class = "like">
Like
<p id = "like" style = "color:green;">0</p>
</div>
<div class = "dislike">
Dislike
<p id = "dis" style = "color:red;">0</p>
</div>
</div>
<!-- use select to get the items to stay on the page-->
</div>
</div>
</div>
';
}
?>
Any suggestions?
Fix these lines:
$link = mysql_connect("localhost", $db_user, $db_pass) or die(mysql_error());
mysql_select_db("submissions",$link) or die(mysql_error());
$query1 = mysql_query("SELECT actual_quote,poster,formtype FROM data WHERE formtype = 'Question1'",$link);
//delete this-> $info = mysql_fetch_array($query1); ?
while($info = mysql_fetch_array($query1)){

Categories