I'm trying to display 6 items in one page with 3 items in each row. And when the user clicks on the image link it will redirect to another page and display the id. However when the user clicks on the image it does redirect to another page but it shows the id of the last product in the last row of the page, and this is not correct. I'm not sure where I made the mistake. I hope you can look at my code and give me a hint where the mistake lies.
<?PHP
session_start();
function connect()
{
$servername = xxxxxxxx;
$username = xxxxxxxx;
$password = xxxxxxxx;
$dbname = xxxxxxxx;
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
echo 'connection is invalid';
} else {
mysqli_select_db($conn, "mytest");
}
return $conn;
}
function getData()
{
$conn = connect();
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
} else {
$startrow = (int) $_GET['startrow'];
}
$sql = "SELECT * FROM tbl_products LIMIT $startrow, 6";
$getdata = mysqli_query($conn, $sql) or die(mysqli_error());
$cell_img = mysqli_num_rows($getdata);
$i = 0;
$per_row = 3;
echo "<table id='productTumb'><tr id='proRow'>";
$data = '';
while ($row = mysqli_fetch_assoc($getdata)) {
//echo "<a href='ProDet.html'></a>";
echo "<td><a href='test.php'><img style='vertical-align: bottom;' width='218px' height='332px' src='" . $row['products_image'] . "'/ ></a></td>";
$data .= "<td style='background-color:#FF0004'>" . $row['product_name'] . "</td>";
$product_id = $row['products_id'];
$_SESSION['id'] = $product_id;
if (++$i % $per_row == 0 && $i > 0 && $i <= $cell_img) {
echo "</tr><tr>$data</tr><tr>";
$data = '';
}
}
for ($x = 0; $x < $per_row - $i % $per_row; $x++) {
echo "<td></td>";
}
echo "</tr>";
echo "</table>";
echo 'Next >>>';
$prev = $startrow - 5;
if ($prev >= 0)
echo ' <<<< Previous';
}
?>
This line of code $_SESSION['id'] = $product_id; will set last product id to SESSION.(overwrites previous ids)
Try to add product id to the anchor href tag
while ($row = mysqli_fetch_assoc($getdata)) {
echo "<td><a href='test.php?id=".$row['products_id']."'><img style='vertical-align: bottom;' width='218px' height='332px' src='" . $row['products_image'] . "'/ ></a></td>";
......
}
In test.php file get id by below code
if(isset($_GET)){
$pid = $_GET['id'];
echo $pid;
}
hope this will helps you.
Related
How can I add pagination to a search engine results page?
I have build a search engine but there are hundreds of thousands of results for every search so I want to add pages to it.
The results of the search engine are outputted in a table.
I have started to learn php and sql recently...
How can I add those pages?
I have tried this so far but with no success:
<?php
$con = mysqli_connect(xxxx);
mysqli_select_db($con, 'Data') or die("could not find the database!");
$output = '';
$results_per_page = 1000;
//positioning
if(isset($_GET['search']))
{
$starttime = microtime(true); //TIME
$searchkey = $_GET['search'];
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%'") or die("Could not search") ;
$count = mysqli_num_rows($query);
// count number of pages for the search
$number_of_pages = ceil($count/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
// LIMIT
$this_page_first_result = ($page-1)*$results_per_page;
if ($count == 0)
{
echo "</br>";
$output = 'There are no search results !' ;
}
else
{
echo '<table class="myTable">';
echo "<tr><th>aaa</th><th>bbb</th></tr>";
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%' LIMIT " . $this_page_first_result . ',' . $results_per_page" ") or die("Could not search") ;
while ($row = mysqli_fetch_array($query))
{
$email = preg_replace('/(' . $searchkey . ')/i', '<mark>\1</mark>', $row["aaa"]);
$password = $row['bbb'];
echo "<tr><td>";
echo $aaa;
echo "</td><td>";
echo $bbb;
echo "</td></tr>";
$output = '</table>';
}
//echo "</table>";
$endtime = microtime(true);
$duration = $endtime - $starttime;
echo "</br>";
if ($count == 1)
{
echo "<div class=resinfo>";
echo '<div>'."1 result was found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
else
{
echo "<div class=resinfo>";
echo '<div>'."$count results were found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
}
echo $output;
}
//LINKS to other pages
for ($page = 1; $page<=$number_of_pages;$page++){
echo '' . $page . '';
}
?>
What have I done wrong, what can I improve to make it work?
Thanks a lot for your help!
It is not a good idea to build a pagination from scratch, instead use a lib like this: https://github.com/KnpLabs/knp-components/blob/master/doc/pager/intro.md
I am making a tictactoe game with php and mysql. It should be played by 2 players from different systems. So I have a table in mysql with a column id which goes from 1-9 and a column tictac which has a value X or O or NULL. Put a x or o in the database is working but retrieving a X or O out of the table and show it on the screen is not working. I have a config file, a class.tictactoe.php, class.game.php and an index.php. The DB connection should be in the class.tictactoe.php but I don't know how.
I am having the most trouble with this part:
function displayGame()
{
if (!$this->isOver())
{
echo "<div id=\"board\">";
$i=1;
for ($x = 0; $x < 3; $x++)
{
for ($y = 0; $y < 3; $y++)
{
require('config.inc.php');
$db = new PDO("mysql:dbname=$db_name;host=$db_host",
$db_user, $db_pass,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
echo "<div id=\"$i\" class=\"board_cell\">";
$i++;
$query = $db->prepare('SELECT * FROM tictactoe WHERE value IS NOT NULL and id = ?');
if ($this->board[$x][$y])
$query->execute([$lookup[$key]]);
echo "<p>\"{$this->board[$x][$y]}\"</p>";
else
{
echo "<select name=\"{$x}_{$y}\">
<option value=\"\"></option>
<option value=\"{$this->player}\">{$this->player}</option>
</select>";
}
echo "</div>";
}
echo "<div class=\"break\"></div>";
}
echo "
<p align=\"center\">
<input type=\"submit\" name=\"move\" value=\"Take Turn\" /><br/>
<b>It's player {$this->player}'s turn.</b></p>
</div>";
}
else
{
if ($this->isOver() != "Tie")
echo successMsg("Congratulations player " . $this->isOver() . ", you've won the game!");
else if ($this->isOver() == "Tie")
echo errorMsg("Whoops! Looks like you've had a tie game. Want to try again?");
session_destroy();
echo "<p align=\"center\"><input type=\"submit\" name=\"newgame\" value=\"New Game\" /></p>";
}
}
function move($postdata)
{
if ($this->isOver())
return;
require('config.inc.php');
$db = new PDO("mysql:dbname=$db_name;host=$db_host",
$db_user, $db_pass,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$postdata = array_unique($postdata);
$lookup = ['0_0'=>1, '0_1'=>2, '0_2'=>3, '1_0'=>4, '1_1'=>5, '1_2'=>6,
'2_0'=>7, '2_1'=>8, '2_2'=>9];
$query = $db->prepare('UPDATE tictactoe SET tictac = ? WHERE id = ?');
foreach ($postdata as $key => $value)
{
if ($value!=$this->player) continue;
$query->execute([$this->player, $lookup[$key]]);
if ($value == $this->player)
{
$coords = explode("_", $key);
$this->board[$coords[0]][$coords[1]] = $this->player;
if ($this->player == "X")
$this->player = "O";
else
$this->player = "X";
$this->totalMoves++;
}
}
if ($this->isOver())
return;
}
The indentation might be wrong.
I'm quite new to PHP. I'm playing around with connecting to a sqlite database and I've done that successfully. For some reason my pagination is not working.
The value of $page won't go beyond 2. Can someone help me out, I'm sure its probably a simple mistake. (So currently it does change from the first page to the next.
<?php
try
{
//open the database
$db = new PDO('sqlite:client.db');
//create the database
$db->exec("CREATE TABLE IF NOT EXISTS Client (id INTEGER PRIMARY KEY AUTOINCREMENT, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(50), gender VARCHAR(50))");
$page = 1;
if(!empty($_GET['page'])) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false === $page) {
$page = 1;
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//something posted
if (isset($_POST['Previous'])) {
print 'current value of $page = ' . $page;
print "<br>";
if($page <= 0) {
$page = 1;
}else {
$page = $page - 1;
}
} else if(isset($_POST['Next'])) {
print 'current value of $page = ' . $page;
print "<br>";
$page = $page + 1;
}
}
// set the number of items to display per page
$limit = 10;
// build query
$offset = ($page - 1) * $limit;
if($offset <= 0) {
$offset = 0;
}
print '$page = ' . $page;
print "<br>";
print '$offset = ' . $offset;
//now output the data to a simple html table...
print "<table border=1>";
print "<tr><td>Id</td><td>First Name</td><td>Last Name</td><td>Age</td><td>Gender</td></tr>";
$sql = "SELECT * FROM Client LIMIT " . $offset . "," . $limit;
$result = $db->query($sql);
//$rows = count($result);
//print $rows;
//checks if table has data
//$count = $result->fetchColumn();
foreach($result as $row)
{
print "<tr><td>".$row['id']."</td>";
print "<td>".$row['first_name']."</td>";
print "<td>".$row['last_name']."</td>";
print "<td>".$row['email']."</td>";
print "<td>".$row['gender']."</td></tr>";
}
print "</table>";
print "<br>";
//print "<button type=\"button\" name=\"button\"><< Previous </button>";
//print "<button type=\"button\" name=\"button\">Next >></button>";
print "<form class=\"\" action=\"\" method=\"post\">";
print "<button type=\"submit\" name=\"Previous\">Previous</button>";
print "<br><br><button type=\"submit\" name=\"Next\">Next</button>";
print "</form>";
// close the database connection
$db = NULL;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>
All credit goes to Ryan-Vincent for helping me solve this.
Basically, I had everything working, but had the incorrect attribute for the form action.
This is the only thing I changed and it worked fine (this is the opening form tag in html, notice the page url parameter gets its value from the php page variable.
print "<form class=\"\" action=\"?page=$page \" method=\"POST\">";
Hope this helps other php newbies.
I feel like I ask a lot of questions.
Anyways, I'm writing pagination for some database entries, and it looks sound to me but it's only displaying the first 10 posts and nothing else when I click the links.
The whole shebang is right here:
<?php
$post_limit = 10;
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("failed to connect: " . $conn->connect_error);
}
$sql = "SELECT count(id) FROM $tablename";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "you fucked up";
} else {
echo $row["id"];
}
$row = mysqli_fetch_array($result, MYSQL_NUM);
$post_count = $row[0];
if(isset($_GET['page'])) {
$page = $_GET['page'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
}
$post_left = $post_count - ($page * $post_limit);
$sql = "SELECT id, upvotes, downvotes, name, title, message, date, time FROM posts ORDER BY date DESC, time DESC LIMIT $offset, $post_limit";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br><div id='messageBar'>";
echo " ❖ </b>";
echo "Posted by <b>";
echo htmlspecialchars($row["name"]);
echo "</b> on ";
echo $row["date"];
echo " at ";
echo $row["time"];
if (!empty($row['title'])) {
echo " - <b>";
echo htmlspecialchars($row["title"]);
echo "</b>";
}
echo "<span style='float: right'>#";
echo $row["id"];
echo "</span>";
echo "</div><div id='messageContent'>";
echo htmlspecialchars($row["message"]);
echo "<br><br><span id='commentLink'><a class='commentLink' href='thread.php?id=$row[id]'>view thread </a></span>";
echo "<br></div><br><hr>";
}
} else {
echo "<br>";
echo "<center><i>it's dusty in here</i></center>";
echo "<br>";
}
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
$conn->close();
?>
The link for the next page appears at the bottom, but clicking it takes you to the page you're already on with the same 10 most recent posts.
I am trying to learn PHP as I go, so I appreciate any help. Thank you!
Instead of using $_GET please use $_SESSION to manage a counter.
Every time you go in this page you increment the counter.
So, you have to do this on the top of the page:
if(isset($_SESSION['counter'])) {
$page = $_SESSION['counter'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
$_SESSION['counter']=0;
}
Try this.
By the way there is Datatables which do what you're looking for.
P.S. If you don't start sessions in some other points in your code, please put session_start(); in the first page (e.g., login.php) otherwise put on this page.
Fixed. Problem was here:
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
The URL I was linking to wasn't supposed to have spaces around the = sign. It's still buggy, but it works.
This script allows the user to choose a table from the dropdown and then displays the contents of the chosen table.
At the moment the DB connection is working.
A list of tables is shown in the dropdown.
Problem: No content from the database table is shown.
I have checked through the code and everything looks OK, but it still only seems to partially work.
<?php
//update this to your DB connection details.
$dbh = "localhost";
$dbn = "dbname";
$dbu = "dbuser";
$dbp = "dbpass";
$conn = mysql_connect($dbh,$dbu,$dbp) or die("Unable to connect do database.");
mysql_select_db($dbn, $conn) or die("Unable to select database.");
//Some vars for Order by and Limit.
if (!isset($ordBy)){
$ordBy = 1;
}
if (!isset($ps)){
$ps = 0;
}
if (!isset($ord)){
$ord = 1;
}
if ($ord == 1){
$tOrder = "ASC";
} else {
$tOrder = "DESC";
}
//Tables drop-down
$result = mysql_query("SHOW TABLES FROM $dbn") or die("Cannot list table names.");
echo "
<form name=\"table_browser\" action=\"".$PHP_SELF."\" method=\"GET\" >
<select name=\"t\" onChange=\"javascript:submit();\">
<option>Select a table</option>
";
while ($row = mysql_fetch_row($result)){
echo " <option value=".$row[0].">".$row[0]."</option>\n";
}
echo " </select>
</form>\n";
if (!isset($t)){
die("Please select a table");
}
//Get number of rows in $t and then select
$result = mysql_query("SELECT COUNT(*) FROM $t") or die("The requested table doesn't exist.");
$total = mysql_result($result,0);
$qry = "SELECT * FROM $t ORDER BY ".$ordBy." ".$tOrder." LIMIT ".($ps*20).",20 ";
if (isset($qry)) {
$result = mysql_query($qry) or die("The requested table doesn't exist.");
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result);
if (!$meta) {
echo "No information available on the table<br />\n";
}
$name[$i] = $meta->name;
$i++;
}
//Display table details
echo "Rows ".($ps*20+1)." to ".((($ps+1)*20 < $total) ? (($ps+1)*20) : ($total))." of $total from table:
<b>$meta->table</b>\n<br /><br />\n";
//Count results
if ($ps > 0) {
echo "20 Previous - ";
} else {
echo "20 Previous - ";
}
if ((($ps+1)*20) < $total ){
echo "Next 20\n";
} else {
echo "Next 20\n";
}
//Column names
echo "<br /><br />\n<table>\n <tr>\n";
for ($j = 0; $j < $i; $j++){
echo " <td><b>$name[$j]</b>";
if ($ordBy == $name[$j]) {
echo "<img src=\"images/arrow$ord.gif\">";
}
echo "</td>\n";
}
echo " </tr>\n";
//Data
while ($row = mysql_fetch_array($result)){
echo " <tr onmouseover=\"this.style.background='#DDDDDD'\" onmouseout=\"this.style.background=''\">";
for ($j = 0; $j < $i; $j++){
echo "<td>".$row[$name[$j]]."</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
}
mysql_close();
?>
#gentlebreeze - my eyes hurt from trying to read that - but I can't see where you are actually setting the variable called $t - which is used to determine the table. You should have
$t = $_GET['t'];
somewhere before the line:
....if (!isset($t)){....
because you need to use it in the line:
....$result = mysql_query("SELECT COUNT(*) FROM $t"....
and you should not be using mysql_query either - old and now deprecated. You should switch to PDO and bound variables.