What is wrong with this pagination? - php

What is wrong with this code? When I click on 'Next' button it shows empty page and broke my web design? I've trying to figure it out all day but no luck.
<?php
if(isset($_GET['joke_id'])){
$joke_id = $_GET['joke_id'];
$qry = "SELECT * FROM joke WHERE joke_cat = '$joke_id'";
$result = mysqli_query($con, $qry) or die("Query failed: " . mysqli_errno($con));
$line = mysqli_fetch_array($result, MYSQL_BOTH);
if (!$line) echo '';
$previd = -1;
$currid = $line[0];
if (isset($_GET['id'])) {
$previous_ids = array();
do {
$previous_ids[] = $line[0];
$currid = $line[0];
if ($currid == $_GET['id']) break;
$previd = end($previous_ids);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
} while ($line);
}
if ($line) {
echo "<div id=\"box\">";
echo nl2br($line['text']) . "<br /><br />";
echo "</div>";
}
else echo 'Is empty<br/>'; **<------ HERE**
if ($previd > -1)
echo '<span>Prev</span>';
echo str_repeat(' ', 5);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
$query = "select * from joke WHERE joke_cat = '$joke_id' order by RAND() LIMIT 1";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
while ($row = mysqli_fetch_array($result, MYSQL_BOTH)){
echo 'Random';
}
echo str_repeat(' ', 5);
if ($line) echo '<span>Next</span><br /><br />';
echo "</div>\r";
}
?>
Also on the line else echo 'Is empty<br/>'; doesn't matter if there is something .. always shows me 'Is empty'..
UPDATE:
databases are:
joke
id
text
date
joke_cat
and cat_joke is
joke_id
joke_name

change this line:
echo 'Random';
To: not ? after cat_id='.$joke_id.' you need to change &
echo 'Random';
Note: also change next and prev code also...

Your last assigment to $line is null .Therefore you should check in your if not $line but the $previous_ids[] or $currid or the others.

Related

Concat () function or alternative solution in mysql query

I am trying to add a character before/after value in mysql query. but I can't make it work.
This is the part that doesn't work in my case:
$query = "select CONCAT ('.', DuRpt) as DuRpt, DaRpt from DDtb order by DATE DESC";
You can see the full code below. Any ideas why it doesn't work or can I get an alternative solution, please. thanks.
<div class="container">
<div class="left">
<?php
include ("etc/config.php");
$query = "select concat ('.', DuRpt) as DuRpt, DaRpt from DDtb order by DATE DESC";
$result = mysqli_query($link, $query);
if (!$result) {
$message = 'ERROR:' . mysqli_error($link);
return $message;
} else {
$i = 0;
echo '<form name="select" action="" method="GET">';
echo '<select name="mySelect" id="mySelect" size="44" onchange="this.form.submit()">';
while ($i < mysqli_field_count($link)) {
$meta =
mysqli_fetch_field_direct($result, $i);
echo '<option>' . $meta->name . '</option>';
$i = $i + 1;
}
echo '</select>';
echo '</form>';
}
?>
</div>
<div>
<?php
if(isset($_GET['mySelect'])) {
$myselect = $_GET['mySelect'];
$sql = "SELECT `$myselect` as mySelect from DDtb order by DATE DESC";
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
$table_row_counter = 3;
echo '<table>';
while($row = $result->fetch_assoc())
{
$table_row_counter++;
if ($table_row_counter % 30 == 1) {
echo '</table>';
echo '<table>';
}
echo "<tr><td>" . $row["mySelect"] . "</td></tr>";
}
}
}
echo '</table>';
mysqli_close($link);
?>
</div>
</div>
For the 2nd half of your code, you can do this:
note you won't need to concat anything in your initial query
if(isset($_GET['mySelect'])) {
// configure every option here, if there's not pre/postfix, use a blank string
$prepostfixes = [
'DuRpt' => ['.', '.'],
'DaRpt' => ['', ''],
];
$myselect = $_GET['mySelect'];
if (!isset($prepostfixes[$myselect])) {
die ('Unknown Select'); // this will prevent sql injection
}
$sql = "SELECT `$myselect` as mySelect from DDtb order by DATE DESC";
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
$table_row_counter = 3;
echo '<table>';
$prefix = $prepostfixes[$myselect][0];
$postfix = $prepostfixes[$myselect][1];
while($row = $result->fetch_assoc())
{
$table_row_counter++;
if ($table_row_counter % 30 == 1) {
echo '</table>';
echo '<table>';
}
echo "<tr><td>" . $prefix . $row["mySelect"] . $postfix . "</td></tr>";
}
}
}
Just update your code and remove the duplicate of DuRpt from it.
$query = "select concat ('.', DuRpt) as DuRpt from DDtb order by DATE DESC";

Search database using array and then echo/print result in foreach loop using PHP

I need to get variable code from URL so I $codes = $_GET['code']; (url example website.com/update?code[]=7291&code[]=9274&code[]=8264&) then I SELECT firstname FROM guests WHERE invitecode = $codes" then I output data and set as $relatives = $row["firstname"] and then later on in the file I need to echo/print print $relative.
Why is this not working for me?
... connection made ...
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE invitecode = $codes";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
Update:
So now using:
<?php
$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
$thecodes .= (int)$vals . ",";
if($thecodes != "")
{
$thecodes = trim($thecodes, ",");
$sql = "SELECT firstname FROM guests WHERE invitecode IN ($thecodes)";
$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
}
else
{
}
?>
It works but I would like to enter the foreach ($relatives as $relative) { echo $relative; }; into a value like this $message = $firstname . " " . $lastname . " will be coming to your event. " . ;.
In the end it would turn out something like this: $message = $firstname . " " . $lastname . " will be coming to your event. " . foreach ($relatives as $relative) { echo $relative . " "; };.
For some reason it won't work when I combine them.
Use the IN operator for this.
<?php
$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
$thecodes .= (int)$vals . ","; //Loop through making sure each is an int for security reasons (No sqli)
if($thecodes != "") //There is at least one code
{
$thecodes = trim($thecodes, ","); //Remove any additional commas
$sql = "SELECT firstname, lastname FROM guests WHERE invitecode IN ($thecodes)"; //Use the IN operator
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row["firstname"] . " " . $row["lastname"] . "is coming to your event";
}
}
}
else //No codes to be queried
{
}
?>
Can this be a solution for you?
$relatives = array(); // declare array
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE ";
foreach ($codes as $code) $sql .= "invitecode = " . intval($code) . " OR ";
$sql .= "1=2"; // simple way to remove last OR or to make sql valid if there are no codes
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
array_push($relatives, $row["firstname"]);
}
}
foreach ($relatives as $relative) {
print $relative;
}
I think this will work...
... connection made ...
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE invitecode = '$codes'";
$result = mysqli_query($conn, $sql) or die('-1' . mysqli_error());
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo ($row['firstname']);
}
}

Prepared statements doesn't return results

I trying to do all my querys with prepared statements but is new for me and I have some troubles. This is first query and doesn't echo result from table. This is what I've done so far. May be is realy newbie question but is something completely new for me.
if(isset($_GET['joke_id'])){
$joke_id = $_GET['joke_id'];
$qry = $con->prepare("SELECT * FROM joke WHERE joke_cat = ?");
$qry->bind_param('i', $joke_id);
$qry->execute();
$result = $qry->get_result();
$result->fetch_array();
$result = mysqli_query($con, $qry) or die("Query failed: " . mysqli_errno($con));*/
$line = mysqli_fetch_array($result, MYSQL_BOTH);
if (!$line) echo '';
$previd = -1;
$currid = $line[0];
if (isset($_GET['id'])) {
$previous_ids = array();
do {
$previous_ids[] = $line[0];
$currid = $line[0];
if ($currid == $_GET['id']) break;
$previd = end($previous_ids);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
} while ($line);
}
if ($line) {
echo "<div id=\"box\">";
echo nl2br($line['text']) . "<br /><br />";
echo "<div id=\"share\"><span class='st_facebook' displayText='Facebook'></span>
<span class='st_twitter' displayText='Tweet'></span>
<span class='st_googleplus' displayText='Google +'></span></div>";
echo '<br /><br /><br />';
echo "</div>";
}
else echo '<p>Empty category</p><br/>';
This is what I use right now before to try PDO and it's work with no problems.
qry = "SELECT * FROM joke WHERE joke_cat = '$joke_id'";
$result = mysqli_query($con, $qry) or die("Query failed: " . mysqli_errno($con));
$_GET['joke_id'] and $_GET['joke_cat'] is set ?
or try
$qry = $con->prepare("SELECT * FROM joke WHERE joke_cat =:joke_cat");
$qry->bindParam(':joke_cat', $_GET['joke_cat'], PDO::PARAM_STR);
$qry->execute();
$result = $qry->fetchAll();

Catgories didn't work

So I try to learn php and decided to make one site where I add images, save them in folder and id, name,type, path in mysql. Then show on page. So far I have upload form and I can upload and save images. Also I showing them successfully on the page.
Now I'm trying to make categories like - Nature, Funny ... etc. So I added one field in my main table -> img_category.
Also I madded second table - cats whit cat_id and cat_name fields. Using this to show the categories on the page:
<?php
$q = mysqli_query($con,"select * from cats");
while ($res = mysqli_fetch_assoc($q))
{
echo '<a href="pic.php?cat_id='. $res['cat_id'] .'">'.$res['cat_name'].'<br/>';
}
So now how can I make when I click on some category link to load images only from this category?
I have managed to make something like this but it doesn't work like is expected
<?php
$q = mysqli_query($con,"select * from cats");
while ($res = mysqli_fetch_assoc($q))
{
echo '<a href="pic.php?cat_id='. $res['cat_id'] .'">'.$res['cat_name'].'<br/>';
}
?>
<hr>
<?php
$cat_id = $_GET['cat_id'];
$query = "SELECT * FROM images JOIN cats ON images.img_category = cats.cat_id WHERE cats.cat_id = '$cat_id'";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
$line = mysqli_fetch_array($result, MYSQL_BOTH);
if (!$line) echo '';
$previd = -1;
$currid = $line[0];
if (isset($_GET['id'])) {
do {
$currid = $line[0];
if ($currid == $_GET['id']) break;
$previd = $currid;
$line = mysqli_fetch_array($result, MYSQL_BOTH);
} while ($line);
}
if ($line) {
echo "<div id=\"picture\">";
echo "<img style=\"width:100%;margin:0 auto;\" src=\"upload/".$line['name']."\" /></a><br />";
echo "<div id=\"caption\">".$line['caption']."</div><br />";
}
else echo "There is no images!\n";
if ($previd > -1) echo '<span>Prev</span>';
echo str_repeat(' ', 5);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
$query = "select * from images order by RAND() LIMIT 1";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
while ($row = mysqli_fetch_array($result, MYSQL_BOTH)){
echo 'Random';
}
echo str_repeat(' ', 5);
if ($line) echo '<span>Next</span> <br /><br />';
echo "</div>";
?>
The results are:
When there is image in the category is showed but and if I click on 'Next' button I get the same image.
If there is no image in the category I get all echoes like link whit the ID of last category for exam: There is no image like link and if I click it I get last category ID loaded. In my case I have 8 categories so ID=8.
Any help is appreciate!
Thank's
EDIT:
Ok this line:
echo '<span>Следваща</span>
Where is pic.php?cat_id=... i think is wrong. Here I must take next image ID not next category ID. But how to change it for image? If i make it pic.php?id=... I get empty page.
I don't understand it. I know that is messy code but is best I can do for now.
EDIT 2:
I've made something like this. Now can you help me how to make query's for next image because now didn't get next image and stay the same.
$cat_id = $_GET['cat_id'];
$cat_id = mysqli_real_escape_string($con, $cat_id);
$query = "SELECT * FROM images JOIN cats ON images.img_category = cats.cat_id WHERE cats.cat_id = '$cat_id'";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
$prevSQL = mysqli_query($con,"SELECT cat_id FROM cats WHERE cat_id < $cat_id ORDER BY cat_id DESC LIMIT 1") or die (mysqli_error($con));
$nextSQL = mysqli_query($con, "SELECT cat_id FROM cats WHERE cat_id > $cat_id ORDER BY cat_id ASC LIMIT 1") or die (mysqli_error($con));
$prevobj=mysqli_fetch_object($prevSQL);
$nextobj=mysqli_fetch_object($nextSQL);
$pc = mysqli_fetch_object(mysqli_query($con, "SELECT COUNT(cat_id) as pid FROM cats WHERE cat_id<$cat_id ORDER BY cat_id DESC")) or die (mysqli_error($con));
$nc = mysqli_fetch_object(mysqli_query($con, "SELECT COUNT(cat_id) as nid FROM cats WHERE cat_id>$cat_id ORDER BY cat_id ASC")) or die (mysqli_error($con));
$prev=$pc->pid>0 ? 'Prev |' : '';
$next=$nc->nid>0 ? 'Next' : '';
$row = mysqli_fetch_array($result);
echo "<div id=\"picture\">";
echo "<img src=\"upload/" . $row['name'] . "\" alt=\"\" /><br />";
echo $row['caption'] . "<br />";
echo "</p>";
echo $prev;
echo $next;
As you stated, I guess the error is with the line:
echo '<span>Следваща</span>
I think it should be:
echo '<span>Следваща</span>
EDIT:
Your code should look like:
<?php
$q = mysqli_query($con,"select * from cats");
while ($res = mysqli_fetch_assoc($q))
{
echo '<a href="pic.php?cat_id='. $res['cat_id'] .'">'.$res['cat_name'].'<br/>';
}
?>
<hr>
<?php
$cat_id = $_GET['cat_id'];
$query = "SELECT * FROM images JOIN cats ON images.img_category = cats.cat_id WHERE cats.cat_id = '$cat_id'";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
$line = mysqli_fetch_array($result, MYSQL_BOTH);
if (!$line) echo '';
$previd = -1;
$currid = $line[0];
if (isset($_GET['id'])) {
do {
$currid = $line[0];
if ($currid == $_GET['id']) break;
$previd = $currid;
$line = mysqli_fetch_array($result, MYSQL_BOTH);
} while ($line);
}
if ($line) {
echo "<div id=\"picture\">";
echo "<img style=\"width:100%;margin:0 auto;\" src=\"upload/".$line['name']."\" /></a><br />";
echo "<div id=\"caption\">".$line['caption']."</div><br />";
}
else echo "There is no images!\n";
if ($previd > -1) echo '<span>Prev</span>';
echo str_repeat(' ', 5);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
$query = "select * from images order by RAND() LIMIT 1";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
while ($row = mysqli_fetch_array($result, MYSQL_BOTH)){
echo 'Random';
}
echo str_repeat(' ', 5);
if ($line) echo '<span>Next</span> <br /><br />';
echo "</div>";
?>
Try this
<?php
if(isset($_GET['cat_id'])){
$cat_id = $_GET['cat_id'];
$query = "SELECT * FROM images WHERE img_category = '$cat_id'";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
$line = mysqli_fetch_array($result, MYSQL_BOTH);
if (!$line) echo '';
$previd = -1;
$currid = $line[0];
if (isset($_GET['id'])) {
$previous_ids = array();
do {
$previous_ids[] = $line[0];
$currid = $line[0];
if ($currid == $_GET['id']) break;
$previd = end($previous_ids);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
} while ($line);
}
if ($line) {
echo "<div id=\"picture\">";
echo "<img style=\"width:100%;margin:0 auto;\" src=\"upload/".$line['name']."\" /><br />\r";
echo "<div id=\"caption\">".$line['caption']."</div><br />";
}
else echo "There is no images!\n";
if ($previd > -1)
echo '<span>Prev</span>';
echo str_repeat(' ', 5);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
$query = "select * from images WHERE img_category = '$cat_id' order by RAND() LIMIT 1";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
while ($row = mysqli_fetch_array($result, MYSQL_BOTH)){
echo 'Random';
}
echo str_repeat(' ', 5);
if ($line) echo '<span>Next</span> <br /><br />';
echo "</div>\r";
}
?>

PHP doesn't echo text for last row

I'm trying to write a relatively simple twitter query in php with result like this:
from:TravisBenjamin3 OR from:AshleyElisaG OR from:tncvaan ...
This code works accept it doesn't echo the second OR, also I don't want to display an OR on the last row.
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
echo " from:";
echo $row['twitter'];
if ($counter < count($row)) {
echo " OR";
}
}
Some help would be greatly appreciated. Thanks,
<?php
$tweets = array();
while($row = mysql_fetch_array($result)) {
$tweets[] = $row['twitter'];
}
if(count($tweets) > 0) {
echo "from:" . implode(" OR from:", $tweets);
}
?>
$rowCount = mysql_num_rows($result);
while($row = mysql_fetch_array($result)){
$counter++;
echo " from:";
echo $row['twitter'];
if ($counter < $rowCount) {
echo " OR";
}
}
$count = mysql_num_rows($result);
for($r = 0; $r < $count; $r++)
{
$row = mysql_fetch_array($result));
echo " from:";
echo $row['twitter'];
if ($r < ($count - 1))
{
echo " OR";
}
}
Or, even easier:
$search = "";
while($row = mysql_fetch_array($result))
{
$search .= " from:" . $row['twitter'] . " OR";
}
// Cut the last " OR"
$search = substr($search, 0, strlen($search) - 3);
echo $search;
Which is actually a poor man's implementation for implode() suggested by Aaron W..

Categories