Displaying blog posts on HTML page - php

include "connection file";
$query = "SELECT * FROM Blog";
$result = mysqli_query($query);
$num_results = mysqli_num_rows($result);
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<div class="blogEntry"><h4>" . $row['title'] . "</h4><h5>" . $row['date'] . "</h5><p>"
. $row['text'] . "</p></div>";
}
Hi, so, I'm trying to loop through all my blog posts and display them to the page in order so the newest entry is first but I can't seem to get it too work. tried a few different ways and always white screen! Any help would really be appreciated :). I'm also going to add a search function and filters, I don't need this now but any suggestions where to look to find info about implementing these would also be really helpful. Link to where I'm putting this code on my website: http://www.obeytoplay.com/. Thanks!

tried a few different ways and always white screen!
That's because there's a syntax error in your code. Either escape the inner double quotes(") using backslash(\) or use single quotes(').
Method(1):
include "connection file";
$query = "SELECT * FROM Blog";
$result = mysqli_query($query);
$num_results = mysqli_num_rows($result);
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<div class=\"blogEntry\"><h4>" . $row['title'] . "</h4><h5>" . $row['date'] . "</h5><p>" . $row['text'] . "</p></div>";
}
Method(2):
include "connection file";
$query = "SELECT * FROM Blog";
$result = mysqli_query($query);
$num_results = mysqli_num_rows($result);
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<div class='blogEntry'><h4>" . $row['title'] . "</h4><h5>" . $row['date'] . "</h5><p>" . $row['text'] . "</p></div>";
}
I'm trying to loop through all my blog posts and display them to the page in order so the newest entry is first
Use ORDER BY in conjunction with SELECT clause to reorder the result set, like this:
SELECT * FROM Blog ORDER BY column_name DESC/ASC;
Here's the reference:
ORDER BY

Related

Need to Count results of a list created in PHP

Okay I have a list being populated and echoed out on a page.
$sql = "SELECT * FROM `game_toe` WHERE `owner`='$mech_units'";
$mydata = mysql_query($sql);
while($record = mysql_fetch_array($mydata)){
echo "<td>" . $record['units'] . "</td>";
Now the results fluctuate depending on the number of 'mech_units' there are. What I need is to display how many are being displayed in the list. Any suggestions?
you can use built in function mysql_num_rows($mydata). This will give you the total number of records that are fetched.
First of all, I would suggest using mysqli.
You could declare a variable which increases by one every time you echo a 'mech_unit'.
$sql = "SELECT * FROM `game_toe` WHERE `owner`='$mech_units'";
$mydata = mysql_query($sql);
$i = 0;
while($record = mysql_fetch_array($mydata)){
$i++;
echo "<td>" . $record['units'] . "</td>";
}
echo "There are " . $i . " mech_units.";
Another option would be to use the mysql_num_rows() function.

Simple query not pulling from database

I cannot figure this out, it's not an error as such, but when i try to echo out the results of a query:
echo "SELECT * FROM `active_customers` WHERE `cus_email`='".$k."' AND `cus_product`='".$_GET['product']."'" . "<br />";
$q = mysql_query("SELECT * FROM `active_customers` WHERE `cus_email`='".$k."' AND `cus_product`='".$_GET['product']."'");
$a = mysql_fetch_array($r);
$n = mysql_num_rows($q);
echo "Number of rows:" . $n;
echo $a['cus_id'];
echo $a['cus_email'];
The number of posts is returning the correct number which is 1, these values $a['cus_id']; and $a['cus_email']; are not coming through at all, i even did a mysql query in phpmyadmin and it works there.
can anyone see what i have done wrong?
correct code can be
echo "SELECT * FROM `active_customers` WHERE `cus_email`='".$k."' AND `cus_product`='".$_GET['product']."'" . "<br />";
$q = mysql_query("SELECT * FROM `active_customers` WHERE `cus_email`='".$k."' AND `cus_product`='".$_GET['product']."'");
$n = mysql_num_rows($q);
echo "Number of rows:" . $n;
while($row = mysql_fetch_array($q, MYSQL_ASSOC)){
echo $row['cus_id'];
echo $row['cus_email'];
}
Although i would recommend using mysqli or PDO for sql databases

full text ranking [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
how to have ranking based on how many words match user input
How can I have a search engine ranked by amount of words that are typed in and ranked by the amount of types they crop up in the fields title, description, keywords, link.
So the higher results are ordered by having more of the words that the user submitted. Say if the user typed in iPhone, iPhone key word crops up in the link, description and title field, so that would be ranked higher than say Apple which mentions it only in the description and Apple Store which mentions it in the title and the description.
My code is below:
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " AND ";
}
$query .= "Match(title, description, keywords, link) Against ('".implode(' ',$terms)." IN BOOLEAN MODE') ";
}
$secs = microtime();
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
echo '<p class="time">Qlick showed your results in ' . number_format($secs,2) . ' seconds.</p>';
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title1 = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$rank = $row['rank'];
$title = substr($title1,0,60);
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p class="kk">' . $description . '<br><br><span class="keywords">' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords">' . PHP_EOL;
}
While I'm sure it is possible to implement this within mysql, a full-text search index like solr/lucene is designed to handle this stuff directly. You might find better resources & help going down that road.
Using php, copy the array returned by the mysql query:
while ($row = mysql_fetch_assoc($query))
{
$rows[] = $row;
}
Then you can loop over $rows and assign a score to
foreach ($rows as $row)
$row['score'] = score_row($row, $terms)
score_row is a helper method that returns a bigger score depending on which columns have which terms and your definition of "importance".
Then sort thw rows by score, then print the results as you were doing.

PHP: using SQL result in a loop without re-executing query

I am trying to add 3 combo boxes which all display the exact same information that comes from my MySQL db. It seems like the code I wrote makes the entire page wait until all 3 combo boxes are populated, before continuing.
<?
$query = "Select * from tblWriters order by surname";
for ($i = 1; $i <= 3; $i++) {
$result = mysql_query($query);
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] . ", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}
?>
I would like to optimize this piece of code, so the query will not be executed 3 times, as I believe this is where the page slows down.
If I put
$result = mysql_query($query);
outside of the for loop, the 2nd and 3rd combo box do not populate. I tried looking into resetting the pointer of the result, but I can't seem to figure out how that works.
Also, is there a way I can reuse the while loop, so I don't have to execute it 3 times?
Can someone point me in the right direction?
I'm pretty new to PHP and trying to learn on my own. Any help would be much appreciated. Thanks!
If you move your mysql_query() out of the loop again, you can reset your mysql-result-pointer by using mysql_data_seek() at the beginning or end of your loop.
This will result in:
mysql_query($query);
for($i=1;$i<=3;$i++);
{
mysql_data_seek(0); // reset datapointer
// output querydata
}
I'm obliged however to point out that the mysql-extension is deprecated by now and you should use mysqli or pdo for new projects and code.
Cache the query result in an array, then generate your markup:
$query = "Select * from tblWriters order by surname";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result))
{
$data[] = $row;
}
for ($i = 1; $i <= 3; $i++) {
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
foreach ($data as $row) {
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] .
", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}

no results shown when I enter the if statement

This is the part of the PHP code I am having the issue:
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_fetch_array($result) == False) echo "Sorry, no clients found";
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo "<br />";
echo $list;
}
Even if I insert an existing idcard value I get no output when there is the if statement, an incorrect idcard displays "Sorry, no clients found" fine. However if I remove the if statement if I enter an existing idcard the data displays ok.
Can you let me know what is wrong with the code please ?
Thanks
Use mysqli_num_rows to count the results:
if(mysqli_num_rows($result) == 0) echo "Sorry, no clients found";
mysqli_fetch_array() fetches an item from the database.
This means your if() code fetches a first item from the database.
Then, when you call mysqli_fetch_array() again from the while() condition, the first item has already been fetched, and you are trying to fetch the second one ; which does not exist.
You must ensure that you use the result from mysqli_fetch_array() and not call it one time just for nothing ; or, as an alternative, you could use the mysqli_num_rows() function (quoting) :
Returns the number of rows in the result set.
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
}else{
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo $list . "<br />";
}
}
Try this.
EDITED: Added closing bracket.
Use mysqli_num_rows() to test if there is anything returned.
Imagine you put some money in your pocket.
Eventually an idea came to your mind to see if you are still have the money.
You are taking it out and count them. All right.
Still holding them in hand you decided to take them from pocket. Oops! The pocket is empty!
That's your problem.
To see if you got any rows from the database you can use mysqli_num_rows(). It will return the number of bills, without fetching them from the pocket.
The problem is, that you try to use mysqli_fetch_array to queck for the number of results. mysqli_fetch_array will fetch the first result, compare it to false and then discard it. The next mysqli_fetch_array will then fetch the second result, which is not existing.
If you want to check if any clients where found, you can use mysqli_num_rows like this:
$idcard = mysqli_escape_string($dbc, $idcard); // See below: Prevents SQL injection
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query) or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
} else {
while($row = mysqli_fetch_array($result)) {
// Do whatever you want
}
}
If $idcard is a user supplied value, please look out for SQL injection attacks.

Categories