I'm working on a Content Management System using PHP for controlling over my Telegram Bot. Basically what I have done till now is that I can read the messages that people has sent to my Telegram Bot and answer to them.
In order to do that, I coded this:
<?php
$botToken = '423495534:asdsadsadasdsadsa';
$website = 'https://api.telegram.org/bot'.$botToken;
$update = file_get_contents($website."/getUpdates");
$updateArray = json_decode($update, TRUE);
$info = file_get_contents($website."/getme");
$infoArray = json_decode($info, TRUE);
$num = count($updateArray["result"]);
$sender_ids = array();
$sender_infos = array();
for($i=0;$i<$num;$i++){
$sender_id = $updateArray["result"][$i]["message"]["from"]["id"];
$sender_isbot = $updateArray["result"][$i]["message"]["from"]["is_bot"];
$sender_fname = $updateArray["result"][$i]["message"]["from"]["first_name"];
$sender_lname = $updateArray["result"][$i]["message"]["from"]["last_name"];
$sender_uname = $updateArray["result"][$i]["message"]["from"]["username"];
$sender_type = $updateArray["result"][$i]["message"]["chat"]["type"];
$sender_msg = $updateArray["result"][$i]["message"]["text"];
$sender_date = $updateArray["result"][$i]["message"]["date"];
if(false === $key = array_search($sender_id, $sender_ids)){
$sender_ids[] = $sender_id;
$sender_infos[] = [
'sender_id' => $sender_id,
'sender_isbot' => $sender_isbot,
'sender_fname' => $sender_fname,
'sender_lname' => $sender_lname,
'sender_uname' => $sender_uname,
'sender_type' => $sender_type,
'sender_msg' => [$sender_msg],
'sender_date' => [$sender_date]
];
}else{
$sender_infos[$key]['sender_msg'][] = $sender_msg;
$sender_infos[$key]['sender_date'][] = $sender_date;
}
}
$num2 = count($sender_ids);
for($j=0;$j<$num2;$j++){
$id = $sender_infos[$j]["sender_id"];
$first_name = $sender_infos[$j]["sender_fname"];
$last_name = $sender_infos[$j]["sender_lname"];
$username = $sender_infos[$j]["sender_uname"];
$messages = $sender_infos[$j]["sender_msg"];
$acc_type = $sender_infos[$j]["sender_type"];
$isbot = $sender_infos[$j]["sender_isbot"];
$num1 = count($messages);
echo '
<div class="col-md-3">
<div class="box box-danger direct-chat direct-chat-danger">
<div class="box-header with-border">
<h3 class="box-title">'.$first_name.'</h3>
<sup>'.$acc_type.' - '.$isbot.'</sup>
<div class="box-tools pull-right">
<span data-toggle="tooltip" title="'.$num1.' New Messages" class="badge bg-red">'.$num1.'</span>
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
<button type="button" class="btn btn-box-tool" data-toggle="tooltip" title="Contacts" data-widget="chat-pane-toggle">
<i class="fa fa-comments"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
</div>
<div class="box-body">
<div class="direct-chat-messages">
<div class="direct-chat-msg">
<div class="direct-chat-info clearfix">
<span class="direct-chat-name pull-left">';
echo '<strong>'.$first_name.'</strong>';
echo '
</span>
</div>';
for($i=0;$i<$num1;$i++){
echo '<div class="direct-chat-text">';
$text = $sender_infos[$j]["sender_msg"][$i];
if($text[0] === '/') {
echo ''.$text.'';
}else{
echo $text;
}
echo '<span class="direct-chat-timestamp pull-right">';
// echo date('l', $sender_infos[$j]["sender_date"][$i]);
echo '</span>';
echo '</div>';
}
echo '
</div>
<div class="direct-chat-msg right">
<div class="direct-chat-info clearfix">
<span class="direct-chat-name pull-right">'.$bot_fname.'</span>
</div>
<img class="direct-chat-img" src="
';
if ($dataSet->GetAvatar() != NULL){
echo $dataSet->GetAvatar();
}else{
echo "img/noprofilepic.jpg";
}
echo '
" alt="Message User Image">
';
$num3 = count($request_params["text"]);
foreach($_SESSION['messages'] as $reply){
echo '<div class="direct-chat-text">';
echo $reply;
echo '</div>';
}
echo '
</div>
</div>
<div class="direct-chat-contacts">
<ul class="contacts-list">
<li>
<a href="#">
<div class="contacts-list-info">
<span class="contacts-list-name">
';
echo $first_name = $sender_infos[$j]["sender_fname"];
echo ' </br> ';
echo $last_name = $sender_infos[$j]["sender_lname"];
echo ' </br> ';
echo ' <a target="_blank" href="http://www.t.me/'.$username.'">'.$username.'</a>';
echo ' </br> ';
echo ' <small class="contacts-list-date pull-right">'.$id.'</small>
</span>
<span class="contacts-list-msg">QUOTE</span>
</div>
</a>
</li>
</ul>
</div>
</div>';
if (isset($_POST['send'])){
$pm = $_POST['message'];
array_push($_SESSION['messages'], $pm);
$request_params = [
'chat_id' => $id,
'text' => $pm
];
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=telegrambots.php?user_name=".$user_name."'>";
$request_url = 'https://api.telegram.org/bot' . $botToken . '/sendMessage?' . http_build_query($request_params);
$response = file_get_contents($request_url);
}
echo '
<div class="box-footer">
<form action="" method="post">
<div class="input-group">
<input type="text" name="message" placeholder="Write your direct message" class="form-control">
<span class="input-group-btn">
<input name="send" type="submit" class="btn btn-danger btn-flat"/>
</span>
</div>
</form>
</div>
</div>
</div>
';
}
?>
Basically what it does is that it grabs the latest updates of my Bot and count the number of results and save it in $num. Then with a for loop I tried to divide every information about the user who has sent message. After that I store all the required information of sender in a separated array called $sender_infos. And the next for loop shows a basic Chat Box depending on the number of users.
This whole thing makes this:
So it works fine and perfect but the problem is that, whenever I try answering to one conversation, it sends the message to all the available users. This issue comes from the for loop which divides every users by the Chat Box.
However what I want to do is to send a SINGLE DIRECT MESSAGE to a CUSTOM user and NOT ALL OF THEM.
I hope I have explained my problem well, so you could understand. If not, please comment me for more information and additional updates.
NOTE: I don't want a quick answer to this question. Because I'm facing this for several days and I don't know how to solve it. Please make sure you understand what I'm asking for and then add your suggest.
Thanks in advance...
Related
My aim is to delete a row whenever I click delete button. My method doing this is by passing the value of ['movies_id'] and storing it inside a hidden input and then passing it when delete button is pressed. The issue is that when I press the delete button it only reads the first id, which in this case is 1. Even though I press the delete button in the 3 card for example. So, my question is how do I pass the correct 'movies_id' stored inside 'keyToDelete' so that it doesn't always read 1?
As you can see in the image below, the id from mysql is being read well inside the card.
function displayMovies()
{
global $dbc;
$movieSelect = "SELECT * FROM movies_tbl";
$query = mysqli_query($dbc, $movieSelect);
if (mysqli_num_rows($query) == 0) {
echo "There is nothing to display.";
} else {
$edit = "";
$delete = "";
if (isset($_SESSION['type'])) {
if ($_SESSION['type'] == "admin") {
$edit = "<a href='#' class='btn btn-cyan align-self-end'>Edit</a>";
$delete = '<input type = "submit" name="delete" value="Delete" form="movieForm" class="btn btn-cyan align-self-end">';
while ($row = mysqli_fetch_assoc($query)) {
movieDesc($row['movies_id'], $row['movie_title'], $row['main_actor'], $row['movie_length'], $row['average_rating'], $row['release_date'], $row['description'], $row['img_path'], $row['trailer_url'], $edit, $delete);
}
} else if ($_SESSION['type'] == "user") {
while ($row = mysqli_fetch_assoc($query)) {
movieDesc($row['movies_id'],$row['movie_title'], $row['main_actor'], $row['movie_length'], $row['average_rating'], $row['release_date'], $row['description'], $row['img_path'], $row['trailer_url'], $edit, $delete);
}
}
} else {
for ($i = 1; $i < 4; $i++) {
$row = mysqli_fetch_assoc($query);
movieDesc($row['movies_id'],$row['movie_title'], $row['main_actor'], $row['movie_length'], $row['average_rating'], $row['release_date'], $row['description'], $row['img_path'], $row['trailer_url'], $edit, $delete);
}
}
}
}
if (isset($_POST['delete'])){
$key = $_POST['keyToDelete'];
echo"<h1>$key</h1>";
}
function movieDesc($movies_id,$movie_title, $main_actor, $movie_length, $average_rating, $release_date, $description, $img_path, $trailer_url, $edit, $delete)
{
echo '<div class="col-md-4 mb-4">
<div class="card">
<img src="images/' . $img_path . '.jpg" class="card-img-top cardImage">
<div class="card-body d-flex flex-column">
<form action="movies.php" id="movieForm" method="post">
<h3 class="card-title text-center fontEDO">' . $movie_title, $movies_id . '</h3>
<div class="row">
<div class="col">
<p class="card-text text-left"><b>Main Actor:</b></p>
<p class="card-text text-left"><b>Movie Length:</b></p>
<p class="card-text text-left"><b>Average Rating:</b></p>
<p class="card-text text-left"><b>Release Date:</b></p>
</div>
<div class="col">
<p class="card-text text-left">' . $main_actor . '</p>
<p class="card-text text-left">' . $movie_length . '</p>
<p class="card-text text-left">' . $average_rating . '</p>
<p class="card-text text-left">' . $release_date . '</p>
</div>
</div>
<p class="card-text text-left description"><br><b>Description:</b> ' . $description . '</p>
<input type="text" name="keyToDelete" value='. $movies_id .'>
</form>
<div class="mt-auto text-center">
Watch Trailer
' . $edit . '
' . $delete . '
</div>
</div>
</div>
</div>';
}
You can't have duplicate id="movieForm". When you use form="movieForm" in the submit button, it submits the first form with that ID, not the one just before the button.
You should move the submit button inside the form, and get rid of form="movieForm" from the button.
Or give each form a unique ID, and use that in the form attribute of the submit button.
Hello I have Two files one file contain the main posts and second file contain load more posts code
Following are the code of main file but in this file i have a problem that i have to loop my all mysql rows in php and i can do it using while loop but when i try this i am getting all rows but after 15 rows it shows only those that are after 15 rows like only 16 row
My main.php code
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$nv_name_split = str_replace('_', ' ', $row['novel_name']);
echo '<br><a href="episode?novel='.$row['novel_name'].'&episode='.$row['episode_num'].'"><figure class="snip1253"><div class="image"><img width="100%"src="images/sneakpeaks/'.$row['sneak_peak'].'" alt="sample59"/></div><figcaption>'.
'<div class="date"><span class="day">'.$row['day'].'</span><span class="month">'.$row['month'].'</span></div><h3>Episode # '.$row['episode_num'].'</h3> <footer>
<div class="writer text-center"><i class="fa fa-book"> '.$nv_name_split.'</i></div>
<div class="love"><i class="fa fa-thumbs-up"></i>'.$row['likes'].'</div>
<div class="comments"><i class="fa fa-comments"></i>'.$row['comments'].'</div></footer></figure></a></figcaption><br><br>';
}
?>
<?php
$stmt_count = $novel_list->runQuery("SELECT episode_num
FROM posts
WHERE just_skpk='0'");
$stmt_count->execute();
while ($rows = $stmt_count->fetch(PDO::FETCH_ASSOC)) {
$count_row = $rows['episode_num'];
}
if ($limit < $count_row) {
echo'<form id="frm_more_post">
<center>
<button type="submit" class="form-control btn btn-load_more" id="frm_btn_more">Load More Posts</button>
</center>
</form>
<br>
<br>';
}else{
echo'<form id="frm_more_post">
<center>
<button type="submit" disabled class="disabled form-control btn btn-load_more" id="frm_btn_more">No More Posts</button>
</center>
</form>
<br>
<br>';
}
and this is my load_more.php code where i post limit of posts using ajax
load_more.php code
$novel_list = new USER();
if (isset($_POST['page'])) {
$limit = $_POST['page']+3;
$stmt = $novel_list->runQuery("SELECT *
FROM posts
WHERE just_skpk='0'
ORDER BY id DESC
LIMIT $limit");
$stmt->execute();
if ($stmt->rowCount(0)) {
echo '<input class="hidden" id="pages" value="'.$limit.'"/>';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$nv_name_split = str_replace('_', ' ', $row['novel_name']);
echo '<br><a data-pages="'.$limit.'" href="episode?novel='.$row['novel_name'].'&episode='.$row['episode_num'].'"><figure class="snip1253"><div class="image"><img width="100%"src="images/sneakpeaks/'.$row['sneak_peak'].'" alt="sample59"/></div><figcaption>'.
'<div class="date"><span class="day">'.$row['day'].'</span><span class="month">'.$row['month'].'</span></div><h3>Episode # '.$row['episode_num'].'</h3> <footer>
<div class="writer text-center"><i class="fa fa-book"> '.$nv_name_split.'</i></div>
<div class="love"><i class="fa fa-thumbs-up"></i>'.$row['likes'].'</div>
<div class="comments"><i class="fa fa-comments"></i>'.$row['comments'].'</div></footer></figure></a></figcaption><br><br>';
}
$stmt_count = $novel_list->runQuery("SELECT episode_num
FROM posts
WHERE just_skpk='0'");
$stmt_count->execute();
while ($rows == $stmt_count->fetch(PDO::FETCH_ASSOC)) {
$count_row = $rows['episode_num'];
}
if ($limit < $count_row) {
echo '<form id="frm_more_post">
<center>
<button type="submit" class="form-control btn btn-load_more" id="frm_btn_more">Load More Posts</button>
</center>
</form>
<br>
<br>';
}else{
echo '<form id="frm_more_post">
<center>
<button type="submit" disabled class="disabled form-control btn btn-load_more" id="frm_btn_more">No More Posts</button>
</center>
</form>
<br>
<br>';
}
}else{
echo 0 ;
}
}
i solve first problem in main.php while loop using double == in while loop but in load_more.php file i cant show more posts button it shows disabled but when i have less than 15 rows in database its working perfectly please help me to show load more posts button in load_more.php.
ThankYou,
Any help will be appreciated.
In your code you are getting episode_num as $count_row, but it should be no of rows. Try below code
$novel_list = new USER();
if (isset($_POST['page'])) {
$limit = $_POST['page']+3;
$stmt = $novel_list->runQuery("SELECT *
FROM posts
WHERE just_skpk='0'
ORDER BY id DESC
LIMIT $limit");
$stmt->execute();
if ($stmt->rowCount(0)) {
echo '<input class="hidden" id="pages" value="'.$limit.'"/>';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$nv_name_split = str_replace('_', ' ', $row['novel_name']);
echo '<br><a data-pages="'.$limit.'" href="episode?novel='.$row['novel_name'].'&episode='.$row['episode_num'].'"><figure class="snip1253"><div class="image"><img width="100%"src="images/sneakpeaks/'.$row['sneak_peak'].'" alt="sample59"/></div><figcaption>'.
'<div class="date"><span class="day">'.$row['day'].'</span><span class="month">'.$row['month'].'</span></div><h3>Episode # '.$row['episode_num'].'</h3> <footer>
<div class="writer text-center"><i class="fa fa-book"> '.$nv_name_split.'</i></div>
<div class="love"><i class="fa fa-thumbs-up"></i>'.$row['likes'].'</div>
<div class="comments"><i class="fa fa-comments"></i>'.$row['comments'].'</div></footer></figure></a></figcaption><br><br>';
}
$stmt_count = $novel_list->runQuery("SELECT count(*) as cnt
FROM posts
WHERE just_skpk='0'");
$stmt_count->execute();
while ($rows = $stmt_count->fetch(PDO::FETCH_ASSOC)) {
$count_row = $rows['cnt'];
}
if ($limit < $count_row) {
echo '<form id="frm_more_post">
<center>
<button type="submit" class="form-control btn btn-load_more" id="frm_btn_more">Load More Posts</button>
</center>
</form>
<br>
<br>';
}else{
echo '<form id="frm_more_post">
<center>
<button type="submit" disabled class="disabled form-control btn btn-load_more" id="frm_btn_more">No More Posts</button>
</center>
</form>
<br>
<br>';
}
}else{
echo 0 ;
}
}
I think this because of the pagination. In the file load_more.php, you are setting a limit
$limit = $_POST['page']+3;
and in the file, main.php
if ($limit < $count_row)
this is the check.
I am trying to post a $_GET value so it cant insert the variable value into the database using $_SERVER["REQUEST_METHOD"].
<?php require_once("../includes/initialize.php"); ?>
<?php include("../includes/form_validation_card.php"); ?>
<?php $username = $_SESSION['username']; ?>
<?php
if(!isset($_GET['total']) && !isset($_GET['order_id'])){
redirect_to('order_summary.php');
}
$total = $_GET['total'];
$order = $_GET['order_id'];
?>
<?php
$username = $_SESSION['username'];
$sql = "SELECT * FROM customers WHERE username='$username'";
$result_set = $database->query($sql);
$found_user = $database->fetch_array($result_set);
?>
<?php include_layout_template('header2.php'); ?>
<div class="container">
<div class="row">
<br/><br/><?php echo output_message($message); ?>
</div>
<div class="row ">
<div class="jumbo jumbotron-fluid mx-auto d-block" style="height: 500px; width: 440px; background-color:#DCDCDC; border-radius: 5px;" >
<div class="text-center" style="margin: 3px;"><img src="logo/eden_petshop_logo.png" width="32" height="32"/><?php echo $found_user['first_name']; ?> <?php echo $found_user['last_name']; ?></div>
<p class="text-center">order id: #<?php echo $order; ?></p>
<h4 class="display-4 lead text-center">N<?php echo $total; ?></h4>
<div class="col-sm-6 col-sm-offset-3 mx-auto d-block">
<?php echo output_message($message); ?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post" class="form-horizontal">
<div class="form-group">
<div class="col">
<input type="text" name="card_number" onchange="trim(this)" placeholder="Card Number" class="form-control" id="card_number"/>
<span style="color: #EA4335"><?= $card_number_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<input type="text" name="mm_yy" class="form-control" onchange="trim(this)" placeholder="MM/YY">
<span style="color: #EA4335"><?= $mm_yy_error; ?></span>
</div>
<div class="col">
<input type="password" name="cvv" class="form-control" onchange="trim(this)" placeholder="CVV">
<span style="color: #EA4335"><?= $cvv_error; ?></span>
</div>
</div>
</div>
<div class="col-sm-12 col-sm-push-3">
<button type="submit" name="submit" value="Pay" class="btn bg-info btn-sm btn-block" onClick="return confirm('Are you sure your details are correct?');">Pay</button>
</div>
</form>
</div>
</div>
</div>
<?php include_layout_template('footer2.php'); ?>
This is the input display page but i am trying to the $total and $order $_GET variables insert into the database... Please note that every other part of the code assignment is working fine.
<?php
//define variables and set them to empty values
$total_error = $order_error = $card_number_error = $mm_yy_error = $cvv_error = "";
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
//form is submitted with post method
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["card_number"])){
$card_number_error = "<div class=''>Card number is required</div>";
}else{
$card_number = test_input($_POST["card_number"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^(?=.*?[0-9]).{16,}$/",$card_number)){
$card_number_error = "<div>Only 16 numbers allowed</div>";
}
}
if(empty($_POST["mm_yy"])){
$mm_yy_error = "<div class=''>Card expiry is required</div>";
}else{
$mm_yy = test_input($_POST["mm_yy"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^(?=.*?[0-9]).{3,}$/",$mm_yy)){
$mm_yy_error = "<div class=''>Only numbers allowed</div>";
}
}
if(empty($_POST["cvv"])){
$cvv_error = "<div class=''>Card verification is required</div>";
}else {
$cvv = test_input($_POST["cvv"]);
//check if username is atleast 7 characters
if(!preg_match("/^(?=.*?[0-9]).{3,}$/",$cvv)){
$cvv_error = "<div class=''>Card verification must not be more than 3 numbers</div>";
}
}
if($card_number_error == "" && $mm_yy_error == "" && $cvv_error == ""){
$token = 'vfjhvbkebecbjDRCWVJEcbkrvlnke24tir7c_zdvbejw968350124';
$token = str_shuffle($token);
$token = substr($token, 0, 15);
$username = $_SESSION['username'];
$sql = "SELECT * FROM customers WHERE username='$username'";
$result_set = $database->query($sql);
$found_user = $database->fetch_array($result_set);
$email = $found_user['email_address'];
$pay = new Payment();
$pay->username = $username;
$pay->order_id = $order;
$pay->total = $total;
$pay->card_number = $card_number;
$pay->expiry = $mm_yy;
$pay->cvv = $cvv;
$pay->transaction_id = $token;
$pay->status = 0;
$pay->created_at = $timestamp;
if($pay->save()){
//$mail = new Mail();
//$mail->email_address = $email_address;
//$mail->send_transaction_confirmation();
unset($_SESSION['shopping_cart']);
$session->message('<div class="btn bg-success">Congratulations!!! Your order has been processed.</div>');
redirect_to('photos.php');
}
}
if(empty($_POST["message"])){
$message = "";
} else{
$message = test_input($_POST["message"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = htmlentities($data);
return $data;
}
?>
Please note that my $order and total are not getting inserted into my database... Any assistance on my preg_match would be appreciated... Thanks in advance.
You need to use $_POST in your broken code instead of $_GET. Notice your working code used $_POST instead, which is why it works.
I have a page that runs off a local webserver that is uses SQLite as its database. As its used local I am not worried about listing all results on one page as they load super fast. I am having an issue with it though as after 500 results are displayed from SQLite3 the formatting goes all wonky and starts stacking them on top of each other. Everything before that is fine. Its written in php. Info was entered into the database using htmlspecialchars so I dont believe that is the issue. The code that builds each record in the loop is
$list = '';
while($row = $results->fetchArray()) {
$id = $row["id"];
$MovieTitle = $row["MovieTitle"];
$MovieYear = $row["MovieDate"];
$MovieRes = $row["MovieRes"];
$FileName = $row["FileName"];
$Summary = $row["Summary"];
$Genres = $row["Genres"];
$PictureLocation = $row["PictureLocation"];
$Rating = $row["Rating"];
$ReleaseDate = $row["ReleaseDate"];
$list .= '<div class="box">
<div class="movie">
<div class="movie-image"><span class="play"><span class="name">'.$MovieTitle.'</span></span><img src="'.$ThumbnailPic.'" alt=""></div>
<div class="rating">
<p>RATING: '.$Rating.'</p>
<div class="stars">
<div class="'.$StarGraphic.'"></div>
</div>
<span class="comments"></span></div>
</div>';
}
and i just echo them them in the html as such
<html>
<body>
<div id="main">
<br>
<?php echo $list; ?>
</div>
</body>
</html>
Your HTML is wrong, you did not close <div class="box"> and <span class="play"> tags properly.
Correct HTML is:
<div class="box">
<div class="movie">
<div class="movie-image">
<span class="play">
<a href="movielist.php?movie='.$FileName.'">
<span class="name">'.$MovieTitle.'</span>
<img src="'.$ThumbnailPic.'" alt="">
</a>
</span>
</div>
<div class="rating">
<p>
RATING: '.$Rating.'
</p>
<div class="stars">
<div class="'.$StarGraphic.'"></div>
</div>
<span class="comments"></span>
</div>
</div>
</div>
Aso, you can have some tags or quotes in your database records. So you have to use escaping your variables before output http://php.net/manual/en/function.htmlspecialchars.php
Something like this:
$list = '';
while($row = $results->fetchArray()) {
$id = htmlspecialchars($row["id"]);
$MovieTitle = htmlspecialchars($row["MovieTitle"]);
$MovieYear = htmlspecialchars($row["MovieDate"]);
$MovieRes = htmlspecialchars($row["MovieRes"]);
$FileName = htmlspecialchars($row["FileName"]);
$Summary = htmlspecialchars($row["Summary"]);
$Genres = htmlspecialchars($row["Genres"]);
$PictureLocation = htmlspecialchars($row["PictureLocation"]);
$Rating = htmlspecialchars($row["Rating"]);
$ReleaseDate = htmlspecialchars($row["ReleaseDate"]);
$list .= '<div class="box">
<div class="movie">
<div class="movie-image"><span class="play"><span class="name">'.$MovieTitle.'</span></span><img src="'.$ThumbnailPic.'" alt=""></div>
<div class="rating">
<p>RATING: '.$Rating.'</p>
<div class="stars">
<div class="'.$StarGraphic.'"></div>
</div>
<span class="comments"></span></div>
</div>';
}
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;
?>