PHP if mysqli query statement - php

I am in the process of creating a website that displays a group of questions, however my problem is checking if the user has answered the question or not, and if they have, display an “Answered” label.
However the currently, It is displayed the “Answered” Label for each and every question, even if the answer is not in the submissions table. Any help would be appreciated.
while($data = mysqli_fetch_row($result)){
if($data[0] != null){
echo('
<div class="col-md-4 col-sm-5">
<div class="panel panel-default text-center">
<div class="panel-heading">
<span class="fa-stack fa-5x">
<i class="fa fa-circle fa-stack-2x text-default"></i>
<i class="fa fa-codepen fa-stack-1x fa-inverse"></i>
</span>
</div>
<div class="panel-body">
');
if($result4 = mysqli_query($mysqli,"SELECT * FROM submissions where teamID='$teamName' and questionID='$data[0]' and status='correct'")){
echo "Answered";
} else{
echo "Not Answered";
}
echo ('
<h4>'.$data[6].' - <small><i>'.$data[8].' points</i></small></h4>
<p>'.$data[7].'</p>
View Question
</div>
</div>
</div>
');} else{
echo "No More Questions";
}
}
I know I am making a basic or stupid error here, So any help appreciated.

//Mysql query to find number of answers for particular question.
$answercount = mysqli_query($mysqli, "SELECT * FROM submissions where teamID='$teamName' and questionID='$data[0]' and status='correct'");
$answercount = mysqli_num_rows($answercount);
//PHP code
if($answercount>0){
echo "Answered";
} else{
echo "Not Answered";
}

you forget mysqli_query("")
if ($result4 = mysqli_query($con, "SELECT * FROM submissions where teamID='$teamName' and questionID='$data[0]' and status='correct'")) {
echo "Answered";
} else {
echo "Not Answered";
}

Related

Bootstrap 4 list group item as a form input value?

I'm redoing the whole post since I had hard time explaining the issue or question.
What this code does:
The user can create a new training session. They can name it and if they want to, they can copy the content from previously created session.
I'm using Bootstrap 4 list group items to show the previous sessions. My problem is that I can not catch the user selection to post the data to activateSaveTrainingSession.php, which includes the SQL query to insert the new data to the database.
I can pass the data from the form to the action php file from inputSessionName -input. As you can see, I've also tried using input type="hidden". It kind of works, but it only uses the $sessionId from the first row it fetches, not the user selection. And thats the problem: how do I catch which list item the user selects, so I can post the data to the activateSaveTrainingSession.php?
<div class="row">
<div class="col-lg-12">
<form class="was-validated" action="activateSaveTrainingSession.php" method="post">
<div class="custom-control">
<div class="form-group">
<label for="inputSessionName" class="float-left"><?php echo $lang['TRAINING_SESSIONNAME_HEADER'] ?></label>
<input type="text" class="form-control" id="inputSessionName" name="inputSessionName" placeholder="Example 1" minlength="3" maxLength="128" required>
<small id="inputSessionNameHelp" class="form-text text-muted">
<?php echo $lang['TRAINING_SESSIONNAME_HELPTEXT'] ?>
</small>
</div>
</div>
<h5 class = "mt-3"><?php echo $lang['TRAINING_COPYSESSION_HEADER'] ?></h5>
<div class="row mt-3">
<div class="col-lg-6 mb-3">
<div class="list-group" id="list-tab" role="tablist">
<a class="list-group-item list-group-item-action active" id="list-doNotCopy-list" data-toggle="list" href="#list-doNotCopy" role="tab" aria-controls="list-doNotCopy">Do not copy</a>
<?php
$stmt = $link->prepare('SELECT `id`, `sessionName`, `createDate` FROM `trainingSessions` WHERE `userId` = ? ORDER BY `id` DESC LIMIT 5');
$stmt->bind_param('i', $currentUserId);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($sessionId, $sessionName, $sessionNameDate);
$sessionCounter = 0;
$tabsArray = array();
if ($stmt->num_rows > 0) {
while ($stmt->fetch()) {
$sessionNameDateFixed = date("d.m.Y", strtotime($sessionNameDate));
$sessionCounter += 1;
$listId = "list-$sessionId-list";
$tabId = "list-$sessionId";
array_push($tabsArray, $sessionId)
?>
<a class="list-group-item list-group-item-action" id="<?php echo $sessionId ?>" data-toggle="list" href="#<?php echo $tabId ?>" role="tab" aria-controls="<?php echo $tabId ?>"><?php echo $sessionName ?><input type='hidden' name='copySession' value='<?php echo $sessionId ?> '/></a>
<?php
}
} else {
echo "No results.";
}
$stmt->close();
echo "Displaying last $sessionCounter records.";
?>
</div>
</div>
<div class="col-lg-6">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade" id="list-doNotCopy" role="tabpanel" aria-labelledby="list-doNotCopy-list">Do not copy data from previous session.</div>
<?php
foreach ($tabsArray as $session) {
$tabsTextArray = array();
$stmt = $link->prepare('SELECT trainingSessions.id, workouts.workoutName, exercises.setNumber, exercises.reps, exercises.weights FROM workouts INNER JOIN exercises ON workouts.id = exercises.workoutId INNER JOIN trainingSessions on trainingSessions.id = exercises.sessionId WHERE exercises.userId = ? AND trainingSessions.id = ? ORDER BY exercises.id DESC');
$stmt->bind_param('ii', $currentUserId, $session);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($sessionId, $workoutName, $set, $reps, $weights);
if ($stmt->num_rows > 0) {
while ($stmt->fetch()) {
$tabText = "<strong>$workoutName</strong> sarja $set, $reps x $weights kg<br>";
array_push($tabsTextArray, $tabText);
}
}
$listId = "list-$sessionId-list";
$tabId = "list-$sessionId";
?>
<div class = "tab-pane fade" id="<?php echo $tabId ?>" role = "tabpanel" aria-labelledby = "<?php echo $listId ?>"><?php
foreach ($tabsTextArray as $text) {
echo "$text";
}
?>
</div>
<?php
}
$stmt->close();
?>
</div>
</div>
</div>
<button type="submit" name="buttonSaveTrainingSession" class="btn btn-success float-left">
<i class="fas fa-sd-card"></i>
<?php echo $lang['TRAINING_BTN_SAVE'] ?>
</button>
</form>
</div>
</div>
activateSaveTrainingSession.php
<?php
require_once('config/sql.php');
include_once('config/common.php');
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
$currentUserId = $_SESSION["currentUserId"];
$submitButton = strip_tags(trim($_POST['buttonSaveTrainingSession']));
if (isset($submitButton)) {
$inputSessioName = filter_var(trim($_POST["inputSessionName"]), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$copySessionID = filter_var(trim($_POST["copySession"]), FILTER_SANITIZE_NUMBER_INT);
if (empty($inputSessioName) && strlen($inputSessioName) < 3 && $inputSessioName > 128) {
header("location: training.php?msg=invalidSessionName");
} else {
echo "Name: $inputSessioName <br>";
echo "ID: $copySessionID";
}
} else {
header("location: 404.php");
}
?>
I think I understand your problem.
You send in the form several fields:
<input type = 'hidden' name = 'copySession' ...>
which have the same name and not in table form! so it is normal that when receiving the request:
$_POST["copySession"]
you get only one and therefore the first.
If you want to send them all, you have to do:
<input type = 'hidden' name = 'copySession[]' ...>
and you get the request as an array.
foreach($_POST["copySession"] as $sessionId){ ... }
If you want to send only one field, you must make them disabled with javascript in real time during the selection.
For example you put in all fields copySession disabled and you add a class to them. Then you add the same class on the button as well and when the user clicks on a button, the field concerned removes the disabled.
With jQuery something like:
//Click on button
$('a.specialClass').on('click', function(){
//Disabled all copySession inputs
$('input[name="copySession"]').prop('disabled', true);
//Let the field concerned able to be send
$('input.specialClass[name="copySession"]').prop('disabled', false);
});
Good luck!

"i want to display number of records using select option with ajax"

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'limit 0,6' at line 1"
"I have write query to select 2 rows with select sub category but when i select option it gives me sql syntax error"
<div class="pull-right">
<div class="page-filter">
<input type="hidden" value="<?php echo $_GET['sub']?>" id="sub_val"/>
<select id="select_menu" onchange="show_all();">
<span class="text-uppercase">Show:</span>
<option value="1">10</option>
<option value="2">20</option>
<option value="3">30</option>
<option value="4">50</option>
</select>
</div>
<?php
$i = $_GET['index'];
$s = $_GET['sub'];
//echo $c;
if(isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
$productPerPage = 6;
$startNum = ($page - 1)* $productPerPage ; // (2-1) * 3
require_once("connection.php");
if($i==0)
{
$result = mysqli_query($con,"select TOP 3 * from products where subcategory='".$s."' order by asc limit ".$startNum.",".$productPerPage) or die(mysqli_error($con));
}
if($i==1)
{
$result = mysqli_query($con,"SELECT TOP 3 * FROM products where subcategory='".$s."' limit ".$startNum.",".$productPerPage) or die(mysqli_error($con));
}
if($i==2)
{
$result = mysqli_query($con,"SELECT TOP 4 * FROM products where subcategory='".$s."' limit ".$startNum.",".$productPerPage) or die(mysqli_error($con));
}
if($i==3)
{
$result = mysqli_query($con,"SELECT TOP 5 * FROM products where subcategory='".$s."' limit ".$startNum.",".$productPerPage) or die(mysqli_error($con));
}
while($row = mysqli_fetch_array($result))
{
?>
<div class="col-md-4 col-sm-6 col-xs-6">
<div class="product product-single">
<div class="product-thumb">
<div class="product-label">
<span><?php echo $row[4];?></span>
<span class="sale"><?php echo $row[5];?></span>
</div>
<button class="main-btn quick-view"><i class="fa fa-search-plus"></i> Quick view</button>
<img src="<?php echo $row[9];?>" height="150" width="100" style="margin-top:60px;"/>
</div>
<div class="product-body">
<h3 class="product-price"><?php echo $row[3];?><del class="product-old-price"><?php echo $row[2];?></del></h3>
<div class="product-rating">
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star-o empty"></i>
</div>
<h2 class="product-name"><?php echo $row[1];?></h2>
<div class="product-btns">
<button class="main-btn icon-btn"><i class="fa fa-heart"></i></button>
<button class="main-btn icon-btn"><i class="fa fa-exchange"></i></button>
<button class="primary-btn add-to-cart"><i class="fa fa-shopping-cart"></i> Add to Cart</button>
</div>
</div>
</div>
</div>
<?php
}
?>
"I want number of records using select option but it gives me sql syntax error"
This error occurs with the MySQL version.
You can use the following query (example):
SELECT * FROM products LIMIT 0,5
In your case:
"SELECT *
FROM products
where subcategory=$s
ORDER BY column_name ASC
LIMIT $startNum , $productPerPage"

How to echo specific elements from a database

I'm trying to echo certain elements from my news table throughout an article. This involves fields such as the author, headline, content and date. At the moment I can only echo the row and any attempt to echo elements in the page itself is either met with small errors or it outputs nothing. I've had a look around and only found people having problems with simply printing out the row database which I can already do.
Basically when I have Author in my article I want to echo author from my database and it will show next to Author. I'm not sure how possible it is as I am yet to find anything on this or I'm overlooking it.
Here is my current PHP file and I've left in the initial part with the article author, date and headline.
<?php
/* Database connection settings */
$host = 'xxxxx';
$user = 'xxxxx';
$pass = 'xxxxx';
$db = 'xxxxx';
$dbconnect=mysqli_connect($host,$user,$pass,$db);
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
$query = mysqli_query($dbconnect, "SELECT * FROM news WHERE news_Id = 1")
or die (mysqli_errr($dbconnect));
while ($row = mysqli_fetch_array($query)) {
echo
"<tr>
<td>{$row['headline']}</td>
<td>{$row['content']}</td>
<td>{$row['author']}</td>
<td>{$row['date']}</td>
</tr>\n";
}
?>
<div class="container-fluid bg">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="container">
<div class="row mb-2">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="news-title">
<h2><?php echo $row['headline']; ?></h2>
</div>
<div class="news-cats">
<ul class="list-unstyled list-inline mb-1">
<li class="list-inline-item">
<i class="fa fa-folder-o text-danger"></i>
<small>Author:</small>
</li>
<li class="list-inline-item">
<i class="fa fa-folder-o text-danger"></i>
<small>Posted:</small>
</li>
</ul>
</div>
<hr>
Since your query only returns one row, a while loop is inappropriate for fetching the data, as at the end of the loop, $row will be left as a false value, thus making any attempt to access e.g. $row['headline'] fail. Change your while loop
while ($row = mysqli_fetch_array($query)) {
to a simple assignment:
$row = mysqli_fetch_array($query) or die(mysqli_error($dbconnect));
Note you have a typo earlier in your code,
or die (mysqli_errr($dbconnect));
should be
or die (mysqli_error($dbconnect));
You are just printing out the result, but don't have a label. You can add one like this:
while ($row = mysqli_fetch_array($query)) {
echo
"<tr>
<td>Headline: {$row['headline']}</td>
<td>Content: {$row['content']}</td>
<td>Author: {$row['author']}</td>
<td>Date: {$row['date']}</td>
</tr>\n";
}

PHP Pagination not working when Records Filter is applied

I have written a PHP script which has option to filter records and display filtered records pagewise.
My Problem:
When I apply the filter, the records are displayed but when I click on any page number it displays all records page wise instead of showing filtered records pagewise.
How can I correct this?
Here is my complete script,
<body>
<form style="background-color:darkorange; font-size: 13px;" id="form1" name="form1" method="post" action="displaydesign.php">
<label>Design Category</label>
<select name="dlocation">
<option value="">All</option>
<?php
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." GROUP BY dlocation ORDER BY dlocation";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<option value='".$row["dlocation"]."'".($row["dlocation"]==$_REQUEST["dlocation"] ? " selected" : "").">".$row["dlocation"]."</option>";
}
?>
</select>
<input type="text" name="string" id="string" value="<?php echo stripcslashes($_REQUEST["string"]); ?>" placeholder="Search by Name or City" />
<input type="submit" name="button" id="button" value="Filter" />
<a style="background-color:white;" href="displaydesign.php"> Reset</a>
</form>
<hr>
<?php
if ($_REQUEST["string"]<>'') {
$search_string = " AND (dname LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR dcity LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%')";
}
if ($_REQUEST["dlocation"]<>'') {
$search_dlocation = " AND dlocation='".mysql_real_escape_string($_REQUEST["dlocation"])."'";
}
$per_page=2; // no.of records per page
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
// Page will start from 0 and Multiple by Per Page
$start_from = ($page-1) * $per_page;
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE did>0".$search_string.$search_dlocation." order by did desc LIMIT $start_from, $per_page";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {?>
<div class="row">
<?php while ($row = mysql_fetch_assoc($sql_result)) { ?>
<div class="col-sm-6">
<div class="card" >
<h3 class="card-header card-success text-center"><?php echo $row['dlocation'] ?></h3>
<img class="card-img-top img-fluid" src="<?php echo $row['dimage'] ?>" alt="Card image cap">
<div class="card-block ">
<h4><span class="badge badge-default">Designer Information</span></h4>
<h5 class="card-title"><?php echo $row['dname'] ?></h5>
<h6 class="card-subtitle mb-2 text-muted "><?php echo ($row['dcity'])?></h6>
<p class="text-right">
<a class="btn btn-danger btn-sm " data-toggle="collapse" href="#collapseExample<?php echo ($row['did'])?>" aria-expanded="false" aria-controls="collapseExample<?php echo ($row['did'])?>">
Know More..
</a>
</p>
<div class="collapse" id="collapseExample<?php echo ($row['did'])?>">
<div class="card card-block">
<h5><span class="badge badge-warning">Contact Info</span></h5>
<h6 class="card-subtitle mb-2 text-muted"><?php echo ($row['demail'])?></h6>
<h6 class="card-subtitle mb-2 text-muted"><?php echo ($row['dmobile'])?></h6>
<h6 class="card-subtitle mb-2 text-muted"><?php echo ($row['daddress'])?></h6>
<h6 class="card-subtitle mb-2 text-muted"><?php echo ($row['dcity'])?></h6>
<h6 class="card-subtitle mb-2 text-muted"><?php echo ($row['dwebsite'])?></h6>
<!--ACCORDION START-->
<div id="accordion<?php echo ($row['did'])?>" role="tablist" aria-multiselectable="true">
<div class="card">
<div class="card-header" role="tab" id="headingOne<?php echo ($row['did'])?>">
<h5 class="mb-0 btn-sm">
<a data-toggle="collapse" data-parent="#accordion<?php echo ($row['did'])?>" href="#collapseOne<?php echo ($row['did'])?>" aria-expanded="true" aria-controls="collapseOne<?php echo ($row['did'])?>">
Image Description
</a>
</h5>
</div>
<div id="collapseOne<?php echo ($row['did'])?>" class="collapse show" role="tabpanel" aria-labelledby="headingOne<?php echo ($row['did'])?>">
<div class="card-block">
<?php echo $row['dimagedescription'] ?>
</div>
</div>
</div>
<div class="card">
<div class="card-header" role="tab" id="headingTwo<?php echo ($row['did'])?>">
<h5 class="mb-0 btn-sm">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion<?php echo ($row['did'])?>" href="#collapseTwo<?php echo ($row['did'])?>" aria-expanded="false" aria-controls="collapseTwo<?php echo ($row['did'])?>">
Software Used
</a>
</h5>
</div>
<div id="collapseTwo<?php echo ($row['did'])?>" class="collapse" role="tabpanel" aria-labelledby="headingTwo<?php echo ($row['did'])?>">
<div class="card-block">
<p class="card-text"><?php echo $row['dsoftwareused'] ?></p>
</div>
</div>
</div>
<div class="card">
<div class="card-header" role="tab" id="headingThree<?php echo ($row['did'])?>">
<h5 class="mb-0 btn-sm">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion<?php echo ($row['did'])?>" href="#collapseThree<?php echo ($row['did'])?>" aria-expanded="false" aria-controls="collapseThree<?php echo ($row['did'])?>">
My Brand Recommendation
</a>
</h5>
</div>
<div id="collapseThree<?php echo ($row['did'])?>" class="collapse" role="tabpanel" aria-labelledby="headingThree<?php echo ($row['did'])?>">
<div class="card-block">
<div class="card">
<ul class="list-group list-group-flush">
<li class="list-group-item"><?php echo $row['dbrandname'] ?></li>
<li class="list-group-item"><?php echo $row['dbrandsegment'] ?></li>
<li class="list-group-item"><?php echo $row['dbrandwebsite'] ?></li>
<li class="list-group-item"><?php echo $row['dbrandemail'] ?></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!--ACCORDION END-->
</div>
</div>
</div>
<div class="card-footer">
<small class="text-muted">Design ID:- <?php echo stripcslashes($row['did']) ?> Submitted on :-<?php echo stripcslashes($row['dsubmissiondate']) ?></small>
<br>
</div>
</div>
</div>
<?php } ?>
</div>
<?php } else { ?>
<h3>No results found for the desired Search.</h3>
<?php } ?>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<div>
<?php //for page numbers display at bottom of page
//Now select all from table for pagination
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE did>0".$search_string.$search_dlocation." order by did desc";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
// Count the total records
$total_records = mysql_num_rows($sql_result);
//Using ceil function to divide the total records on per page
$total_pages = ceil($total_records / $per_page);
//Going to first page
echo "<center><a href='displaydesign.php?page=1'>".'First Page'."</a> ";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='displaydesign.php?page=".$i."'>".$i."</a> ";
};
// Going to last page
echo "<a href='displaydesign.php?page=$total_pages'>".'Last Page'."</a></center> ";
?>
</div>
</body>
I've been looking over your code, and I also setup an SQL-Fiddle (see below) to play around. I was initially thinking that maybe the MySQL query you use doesn't filter right on specific values or doesn't paginate right but filters right. Anyway there are also comments in the fiddle that explain some ideas and assumptions I made.
For what it's worth, pagination and complex SQL queries are non-trivial. They can also be expensive, and while I don't know your current code platform/setup/environment, I would suggest to push logic and things like pagination to the front end or JavaScript wherever possible. PHP works, too, but I'm mostly trying to point out that in my experience complexity for SQL queries often increases more quickly than code because it's a different type of frameset, namely relational versus procedural.
Your code also contains view and business logic together as well as SQL, so to be open with you I might not find the issue or there may be more than one. But I did notice some things looking at your code.
(1) The paginated results for your contacts list query were NOT exclusive by page number - meaning in some cases a row from a previous result would be included in the results.
(2) There is weird behavior if there are every any empty values for your WHERE conditions values -- specifically, $dname, $dcity, $dlocation. I didn't manage to reproduce your exact issue from JUST the SQL in the SQL fiddle, but I'm wondering if you'll see the same issues with some cleanup to the list query.
Fix Suggestions:
Modify SQL query to use rank and an inner-query to exclusive-paginate results and eliminate empty-match issues. In my suggested query below and in the fiddle, I've adjusted the WHERE condition from a AND (b or c) AND d to a AND ( (b or c) or d ) -- while this looks weird, it says "make sure we're matching on a non-empty location (assumed primary selector), or that we have a name or city to filter by". At least one variable must match true for the LIKE condition checks or it won't return a result row for it, whereas the other way required all three matches for a row (which is fine if those values will always be non-empty).
SET #name = "";
SET #city = "";
SET #location = "WA";
SET #per_page = 1;
-- Setting this arbitrarily - looking at different pages
-- mostly verifying yeah, the fetch/ pagination part works.
SET #page = 3;
SET #rownum = 0;
-- Basic Fetch Query used for getting list-for-page
SELECT
results.id, results.name,
results.location, results.city,
results.rank
FROM (
SELECT
c.id AS id
,c.name AS name
,c.location AS location
,c.city AS city
,#rownum := #rownum + 1 AS rank
FROM contacts AS c
-- ,(SELECT #rownum := 0) r
WHERE c.id > 0
AND ( (c.name LIKE #name OR c.city LIKE #city)
OR c.location LIKE #location )
ORDER BY c.id ASC
) AS results
WHERE rank BETWEEN ( (#page-1) * #per_page + 1) AND ( (#page) * #per_page )
Clarification
There are 2 new things going on in this bigger query. One, there is something called an "inner query" being used to pre-select a set of rows. Second, I'm assigning a rank value to use in my final results query to organize the table rows into "paged" results. This is a workaround to trying to use
WHERE ...
LIMIT ((#page-1)*#per_page), #per_page
or even
WHERE ...
LIMIT ((#page-1)*#per_page) OFFSET #per_page
But (see my CREDITS section), apparently one CANNOT use #vars in SQL. You could also work around this in your code by using PHP string templating or something, like you're already doing to inject variables into strings.
SQL Fiddle
Here's that SQL Fiddle to see what assumptions I made and what I was doing:
http://sqlfiddle.com/#!9/d516e/26
Credits
Apparently, one cannot use user variables like #name in the LIMIT-clause, which I did not know before. I found another Stack post to help me with that problem:
Using variable in a LIMIT clause in MySQL

Making query show latest updated

So I have a script that displays all the topics posted with the information about the topic, I was wondering if anybody could help me make it so whenever somebody comments on it or if the post is edited that it will bump it to the first line echod of the query?
function getReplies($id){
$q = #mysql_query("SELECT reply_content, reply_date, reply_by FROM replies WHERE reply_id='$id'");
if(!$q){
echo 'Error: '.mysql_error();
}
$res = mysql_fetch_array($q);
$q2 = #mysql_query("SELECT `topic_subject` FROM `topics` WHERE `topic_id`='$id'");
if(!$q2){
echo 'Error: '.mysql_error();
}
$res2 = mysql_fetch_array($q2);
if($_SESSION['id'] == $res['reply_by']){
echo '<div class="panel panel-default">
<div class="panel-heading"><b>'.$res2['topic_subject'].'</b></div>
<div class="panel-body">
'.nl2br($res['reply_content']).'
</div>
<div class="panel-footer">
Posted By <strong>'.getOwner($res['reply_by']).'</stong>
on <strong>'.$res['reply_date'].'</strong><br />
Edit | Delete
</div>
</div>
</div>';
} else {
echo'<div class="panel panel-default">
<div class="panel-heading"><b>'.$res2['topic_subject'].'</b></div>
<div class="panel-body">
'.nl2br($res['reply_content']).'
</div>
<div class="panel-footer">
Posted By <strong>'.getOwner($res['reply_by']).'</stong>
on <strong>'.$res['reply_date'].'</strong><br />
</div>
</div>
</div>';
}
}
Comments:
Posts:
Topics:
Try to change your first query and grant it an ORDER BY, perhaps?
$q = "SELECT reply_content, reply_date, reply_by
FROM replies
WHERE reply_id='$id'
ORDER BY reply_date DESC";
It would seem to me also, that you are using two queries, where you only really need to be using one.
UPDATE: Optimized code, try not to repeat yourself, and join queries
function getReplies($id) {
$query = "SELECT replies.reply_content,
replies.reply_date,
replies.reply_by
topics.topic_subject
FROM replies,
topics
WHERE replies.reply_id = topics.topic_id
AND replies.reply_id = '$id' " . //<== PS: You should sanitize this $id parameter
" ORDER BY replies.reply_date DESC";
// You can replace the replies.reply_date column by whatever you end up with for sorting
// Important note - Look into mysqli, mysql is deprecated and too old to be used these days.
$q = #mysql_query($query);
if(!$q) {
echo 'Error: '.mysql_error();
}
$res = mysql_fetch_array($q);
$output = '
<div class="panel panel-default">
<div class="panel-heading"><b>'.$res['topic_subject'].'</b></div>
<div class="panel-body">
'.nl2br($res['reply_content']).'
</div>
<div class="panel-footer">
Posted By <strong>'.getOwner($res['reply_by']).'</stong>
on <strong>'.$res['reply_date'].'</strong><br />';
if($_SESSION['id'] == $res['reply_by'])
$output .= 'Edit | Delete';
$output .= '
</div>
</div>
</div>';
echo $output;
}

Categories