Hi guys I have an application that allows users to post content on an empty div. I need some advice on making it scalable as I have to make sure if users are posting a lot of content the browser will not slow down or crash. I am a beginner so please put up with me. So in my code below I have an echo statement that prints out html content. I want to know how to make that function scalable in the long run? should I set the html as a variable then print it? should I encode it with JSON? please advice me as such. Thank-you
PHP Code
<?php
include_once("connection.php");
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//You can use Inner Join to display the matched records in between the two tables
$query = "SELECT * FROM `qpost` A INNER JOIN `user` B ON A.id=B.id ";
$result = $conn->query($query);
if($result) {
} else {
echo "bitch: " . $conn->error;
}
while($row = $result->fetch_assoc()) {
$time = time();
if( $time < $row['logged_time'] + 30) {
echo " <div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'><span class='glyphicon glyphicon-user'> <b>{$row['username']}</b></span>       <span class='glyphicon glyphicon-time'></span> Posted_on: {$row['time']} </h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4>{$row['question']} </h4>
<p> {$row['description']}</p>
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div> ";
}//end if
}//end while
?>
Did you try to separate the data logic and data display ? if you used php MVC framework which will more convenient on your case.
Following is a simple example.
//demo.html code
<?php
include_once("connection.php");
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//You can use Inner Join to display the matched records in between the two tables
$query = "SELECT * FROM `qpost` A INNER JOIN `user` B ON A.id=B.id ";
$result = $conn->query($query);
if ($result) {
} else {
echo "bitch: " . $conn->error;
}
$time = time();
$data_result = array(); // focus on your data logic process
while ($row = $result->fetch_assoc()) {
if ($time < $row['logged_time'] + 30) {
$data_result[] = $row;
}
}
?>
<?php foreach($data_result as $index => $row) { ?>
<div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'><span class='glyphicon glyphicon-user'> <b><?php echo $row['username']?></b></span>
      <span class='glyphicon glyphicon-time'></span> Posted_on: <?php echo $row['time']?>
</h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4><?php echo $row['question']?></h4>
<p> <?php echo $row['description']?></p>
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div>
<?php } ?>
It's fine what you're doing.
However as Eric has said you can exit and re-enter your PHP
You could store the html in a file, grab it using file_get_contents then use sprintf to manipulate it
In a file called "row.html"
<div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'>
<span class='glyphicon glyphicon-user'>
<b>%s</b> <!-- username -->
</span>      
<span class='glyphicon glyphicon-time'>
Posted_on: %s <!-- time -->
</span>
</h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4>%s</h4> <!-- question -->
<p> %s</p> <!-- description -->
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div>
Then in your PHP....
<?php
while($row = $result->fetch_assoc()) {
$time = time();
if( $time < $row['logged_time'] + 30) {
$rowHtml = file_get_contents('row.html');
echo sprintf($rowHtml,
$row['username'],
$row['time'],
$row['question'],
$row['description']);
}
}
?>
I personally like as much abstraction as possible between my languages :)
Good luck!
One way to echo out HTML with PHP is using Heredoc syntax (http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc)
<?php
$name = 'MyName';
echo <<<MYHTML
<p>
My name is <b>"$name"</b>.
</p>
MYHTML;
?>
Related
So I am trying to create a tutorial bookmarker project. The idea is that the bookmarked tutorials are supposed to load when the page opens. I am trying to display the results from the mysql database using php, for some reason the results only display for half a second and then disappear.
I have spent ages trying to figure out how to fix it and have had no luck. I think it might have something to do with the while loop but not sure.
I have created a class that contains the simple load bookmarks function.
<?php
class Bookmarked {
private $con;
public function __construct($con) {
$this->con = $con;
}
public function loadBookmarks(){
$str = "";
$data = mysqli_query($this->con, "SELECT * FROM bookmarked ORDER BY id DESC");
$count = mysqli_num_rows($data);
if($count == 0){
echo "No bookmarks saved";
}
while($row = mysqli_fetch_array($data)){
echo "In while loop";
$tutname = $row['tutname'];
$tutdescription = $row['tutdescription'];
$tuturl = $row['tuturl'];
$date_added = $row['date_added'];
$str .= "<div class='well'>
<h3>$tutname</h3> <hr> <br>
<p>$tutdescription</p> <br>
<a class='btn btn-primary' href='#'><i class='fas fa-check'></i></a>
<a class='btn btn-default' href='$tuturl' target='_blank'><i class='fas fa-search'></i></a>
<a class='btn btn-danger' href='#' onclick='deleteBookmark()'><i class='fas fa-trash'></i></a>
</div>";
}
echo "Out of while loop";
echo $str;
}
}
?>
I am trying to call it as shown below
<?php
include("includes/header.php");
include("includes/classes/Bookmarked.php");
?>
<div class="header">
<h3 class="text-muted">Tutorials Bookmarked</h3>
</div>
<div class="row">
<div class="col-lg-12">
<div id="bookmarksResults">
<?php
$bookmark = new Bookmarked($con);
$bookmark->loadBookmarks(); //Calling the loadBookmarks() function
?>
</div>
</div>
</div>
</body>
</html>
I tried search for an answer but couldn't find anything. If this isn't clear enough I will explain further.
This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 6 years ago.
I'm creating some code to display all the records from a MySQL database into a PHP view.
The query is perfect: using HeidiSQL it retrieves all the values needed:
At the moment, is giving the following error:
How can I debug this?
The code:
<?php $sql = "select * from specials group by Start_Date DESC";
$result = #mysqli_query($sql)
if($result){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<div class='deal-item col-md-12'>
<div class='col-md-4'>
<img src='lascruces_styles/img/deals-img/oil-deal.jpg' alt='' class='deal-thumb'>
<p class='expire'>The deal expires '.$row['End_Date'].'</p>
</div>
<div class='col-md-6 info-container'>
<h2 class='deal-title'>'.$row['Special_Name'].'</h2>
<p class='offer-user'>Offered by
<a href=''>'.$row['Added_By'].'</a></p>
<p class='deal-desc'>'.$row['Description'].'</p>
<div class='share-row'>
<a href='' class='share'>Share this deal</a>
<div class='social'>
<i class='icon-facebook'></i>
<i class='icon-gplus'></i>
<i class='icon-linkedin'></i>
<i class='icon-mail-squared'></i>
</div>
</div>
</div>
<div class='col-md-2 view-deal-container'>
<p class='old-price'>'.$row['Normal_Price'].'</p>
<p class='current-price'>'.$row['Special_Price'].'</p>
<a href=''><div class='view-deal'>
<p>VIEW DEAL</p>
</div>
</a>
</div>
</div>';
mysqli_free_result ($result); // Free up the resources }
}
?>
You're missing a couple of things.The main things are that you're missing the connection parameter in your mysqli_query() call, and your single quotes are messing all your syntax. Try in this manner:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select * from specials group by Start_Date DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="deal-item col-md-12">
<div class="col-md-4">
<img src="lascruces_styles/img/deals-img/oil-deal.jpg" alt="" class="deal-thumb">
<p class="expire">The deal expires ' . $row['End_Date'] . '</p>
</div>
</div>';
}
} else {
echo "0 results";
}
mysqli_close($conn);
You're not quoting your string properly, which is causing syntax errors. You're also mixing mysql_* with mysqli_* here.
I'm assuming the MySQLi connection you're using is called $mysqli here, change it accordingly (or if you're using another API, you need to adapt to use that, APIs don't mix).
Properly quoted it should look something like this.
<?php
$sql = "select * from specials group by Start_Date DESC";
if ($result = mysqli_query($mysqli, $sql)) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<div class='deal-item col-md-12'>
<div class='col-md-4'>
<img src='lascruces_styles/img/deals-img/oil-deal.jpg' alt='' class='deal-thumb'>
<p class='expire'>The deal expires ".$row['End_Date']."</p>
</div>
<div class='col-md-6 info-container'>
<h2 class='deal-title'>".$row['Special_Name']."</h2>
<p class='offer-user'>Offered by
<a href=''>".$row['Added_By']."</a></p>
<p class='deal-desc'>".$row['Description']."</p>
<div class='share-row'>
<a href='' class='share'>Share this deal</a>
<div class='social'>
<i class='icon-facebook'></i>
<i class='icon-gplus'></i>
<i class='icon-linkedin'></i>
<i class='icon-mail-squared'></i>
</div>
</div>
</div>
<div class='col-md-2 view-deal-container'>
<p class='old-price'>".$row['Normal_Price']."</p>
<p class='current-price'>".$row['Special_Price']."</p>
<a href=''><div class='view-deal'>
<p>VIEW DEAL</p>
</div>
</a>
</div>
</div>";
}
mysqli_free_result ($result); // Free up the resources
}
?>
I've been coding PHP for 2 weeks (it's not pretty) and I have not been able to find the answer to my question. I want an admin type user to be able to fill a form and post it to a page where base level users can view the content. I've gotten all of this to work like a charm, but my dilemma is to allow the admin user to include an image as well. Maybe I just don't know what to search for.
Here is the php code and the form for the admin user page:
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
include_once("connection.php");
if (isset($_SESSION['adminid'])) {
$adminid = $_SESSION['adminid'];
$adminemail = $_SESSION['adminemail'];
if ($_POST['submit']) {
$title = $_POST['title'];
$deadline = $_POST['deadline'];
$content = $_POST['content'];
$sql_blog = "INSERT INTO blog (title, deadline, content, logoname) VALUES ('$title', '$deadline', '$content', '$logoname')";
$query_blog = mysqli_query($dbcon, $sql_blog);
echo "<script>alert('Your inquiry has been posted')</script>";
}
} else {
header('Location: index.php');
die();
}
$sql = "SELECT adminid, adminemail, adminpassword, adminname FROM admin WHERE adminemail = '$adminemail' LIMIT 1";
$query = mysqli_query($dbcon, $sql);
if ($query) {
$row = mysqli_fetch_row($query);
$adminname = $row[3];
}
?>
and here is the code for the base level user page: (i commented out the image block where I want the admin's image to be shown.
<main>
<div class="container">
<div class="row topbuffpost">
<h1>business inquiries</h1>
<hr>
<?php
include_once('connection.php');
$sql = "SELECT * FROM blog ORDER BY id DESC";
$result = mysqli_query($dbcon, $sql);
while ($row = mysqli_fetch_array($result)) {
$title = $row['title'];
$content = $row['content'];
$date = strtotime($row['deadline']);
?>
<div class="col-md-4 col-lg-3">
<div class="card hoverable">
<!-- <div class="card-image">
<div class="view overlay hm-white-slight z-depth-1">
<img src="">
<a href="#">
<div class="mask waves-effect">
</div>
</a>
</div>
</div> -->
<div class="card-content">
<h5> <?php echo $title; ?> <br/> <h6>Deadline |<small> <?php echo date("j M, Y", $date); ?> </small> </h6></h5> <br/>
<p> <?php echo $content; ?> </p>
<div class="card-btn text-center">
Read more
<i class="fa fa-lightbulb-o"></i>  propose a plan
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</main>
All of this works perfectly, I just can't figure out how to have an image display in the same way as the title, deadline, and content. Youtube wont help either, too much outdated php + I haven't been coding long enough to really work things out on my own.
You can save all user images under a folder (let's call /images/user) and record the file name into database.
if ($_POST['submit']) {
$title = $_POST['title'];
$deadline = $_POST['deadline'];
$content = $_POST['content'];
$logoname = basename($_FILES["fileToUpload"]["logoname"]; // <-- Make sure your form is ready to submit an file
// Update below as per your need.
$target = 'images/users/' . $logoname;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target);
$sql_blog = "INSERT INTO blog (title, deadline, content, logoname) VALUES ('$title', '$deadline', '$content', '$logoname')";
$query_blog = mysqli_query($dbcon, $sql_blog);
echo "<script>alert('Your inquiry has been posted')</script>";
}
You can then display the image your page
<main>
<div class="container">
<div class="row topbuffpost">
<h1>business inquiries</h1>
<hr>
<?php
include_once('connection.php');
$sql = "SELECT * FROM blog ORDER BY id DESC";
$result = mysqli_query($dbcon, $sql);
while ($row = mysqli_fetch_array($result)) {
$title = $row['title'];
$content = $row['content'];
$date = strtotime($row['deadline']);
$logoname = 'images/user/' . $row['logoname'];
?>
<div class="col-md-4 col-lg-3">
<div class="card hoverable">
<div class="card-image">
<div class="view overlay hm-white-slight z-depth-1">
<img src="<?php echo $logoname; ?>">
<a href="#">
<div class="mask waves-effect">
</div>
</a>
</div>
</div>
<div class="card-content">
<h5> <?php echo $title; ?> <br/> <h6>Deadline |<small> <?php echo date("j M, Y", $date); ?> </small> </h6></h5> <br/>
<p> <?php echo $content; ?> </p>
<div class="card-btn text-center">
Read more
<i class="fa fa-lightbulb-o"></i>  propose a plan
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</main>
<?php session_start();
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'])
{
header('Location: /admin');
}
include 'includes/header.inc'; ?>
<div class="main_content_wrapper">
<div class="main_content limit_main_content_width margin_center p20">
<div class="question_wrapper main_content_content homepage_section" style='margin-top: 20px'>
<div>Ask any cooking related doubts or learn from already answered quesetions.</div>
</div>
<div class="question_wrapper main_content_content homepage_section">
<div class='big_heading'>Ask your doubt</div>
<div class="question_wrapper_content question_div_wrapper mb10">
<div class="question_wrapper_content question_div_wrapper placeholder_text js_main_question_placeholder">Write your question here</div>
<div class='question_wrapper_content question_div_wrapper ask_question_box p20 subtle_border radius3 mb10 js_main_question_value js_main_question_input' contenteditable='true'></div>
<input type="email" class="p20 subtle_border question_wrapper_content email_input js_main_email_value" placeholder='Enter your email here'>
<div class="g-recaptcha mt10" data-sitekey="6LcIo9oSAAAAAPTdolZGu6RoMDybW0Q66-TLTkbV"></div>
</div>
<div class="everyOtherGreenButton inline_middle question_wrapper_content submit_main_question js_submit_main_question center_align">ASK ME NOW</div>
<div class="everyOtherGreenButton inline_middle question_wrapper_content sending_main_question js_sending_main_question center_align noafter">SENDING...</div>
<div class='inline_middle bold question_wrapper_content response_message question_sent_success js_question_sent_success'>Success! You will receive an email when Kavita answers the question. :D</div>
<div class='inline_middle bold question_wrapper_content response_message question_sent_error js_question_sent_error'>There was an unknown error :( Please try again or refresh the page.</div>
</div>
<div class="question_wrapper main_content_content homepage_section">
<div class='big_heading'>Recently answered questions</div>
<div class="recently_answered_wrapper">
<?php
include 'includes/database_login.inc';
$sql_query = "SELECT * FROM posts WHERE published = 1 and deleted = 0 and answered = 1 ORDER BY answered_on DESC LIMIT 5";
$result = mysqli_query($conn, $sql_query);
echo $result->num_rows;
$rowCount = '2';
echo $rowCount;
$p_index = 0;
while($row = mysqli_fetch_assoc($result)) {
?><a href='/post.php?id=<?php echo $row["id"]; ?>' class="recently_answered_wrapper_content recently_answered_question inline_middle subtle_border recent<?php echo $p_index%4; ?>">
<div class="title p10 bold">Q. <?php echo $row['title']; ?></div>
<div class="answer p10" style='padding-top: 0'><?php echo $row['answer']; ?></div>
</a><?php //$p_index++;
}
$conn->close(); ?><a href='/posts.php' class="recently_answered_wrapper_content recently_answered_question noborder view_all_answered_questions inline_middle center_align">
<div class="p10 bold" style="margin-top: 55px;">VIEW ALL ANSWERS</div>
</a>
</div>
</div>
</div>
This is a snippet of my php code. I have somehow figured that the error Unexpected end of file is happening here. But I don't see why.
UPDATE
When I comment out echo $rowCount, it doesnt show any errors.
I'm about to display comments on a page, everything works fine but I want to display the comments from the user first. So, how do I display the user comments from the user_id first? I'm using a while loop to display the comments.
I would be very grateful if anyone could help me. :)
<?php
$sql = "SELECT * FROM `comments` WHERE `post_id`=$pid AND `active`=1 ORDER BY ups-downs DESC";
$result = $mysqli->query($sql);
$count = $result->num_rows;
if($count == 1){
$counttext = "1 Comment";
}else{
$counttext = $count ." Comments";
}
?>
<div class="media-area media-area-small">
<h3 class="text-center"><?php echo $counttext; ?></h3>
<?php
while($row = $result->fetch_assoc()){
$uid = (int)$row["user_id"];
$user = get_user_info($mysqli,$uid);
?>
<div class="media">
<a class="pull-left" href="#">
<div class="avatar">
<img class="media-object" src="<?php echo $user["picture"]; ?>" alt="...">
</div>
</a>
<div class="media-body">
<table width="100%">
<tr valign="middle">
<td align="left"><h4 class="media-heading text-left"><?php echo fb_clear_name($mysqli, $user["id"]); ?></h4></td>
<td align="right"><h6 class="pull-right text-muted"><?php echo $row["ups"] - $row["downs"]; ?> bits</h6></td>
</tr>
</table>
<p><?php echo htmlentities($row["content"]); ?></p>
<div class="media-footer">
<i class="fa fa-reply"></i> Reply
<a href="#" class="pull-right text-muted">
<?php echo $row["timestamp"]; ?>
</a>
</div>
</div>
</div>
<?php
}
?>
Greetings
You can prefilter the data. For example use
$user_comments=array();
$other_comments=array();
while($row = mysql_fetch_assoc($result))
{
if($row['user']==$current_user)
{
$user_comments[]=$row;
}
else
{
$other_comments[]=$row;
}
}
$comments=array_merge($user_comments,$other_comments);
Then you can display the information the way you want to.