i have this php code that fetches images from the database using the userid, then displays all the images in a list form. im trying to paginate the images, in a limit of 5 items per page. but the code is showing only the first page, without a link to the other pages. here's my php code
<?php
include 'connect.php';
$Category = " ";
$query = "SELECT Img_dir, Caption, Category FROM images WHERE Category = '". $_REQUEST['Category'] ."' AND user_id = '". $_SESSION['user_id'] ."' LIMIT 0,5";
$result = mysqli_query($conn,$query);
while ($row=mysqli_fetch_array($result)){
$image = $row["Img_dir"];
$Caption= $row["Caption"];
$Category = $row["Category"];
echo "<dl>";
echo "<dd>$Category    <img src='base64_encode($image)' />   $Caption<dd>";
echo "</dl>";
}
//number of total pages available
$results_per_page = 10;
$number_of_results = mysqli_num_rows($result);
echo $number_of_pages = ceil($number_of_results / $results_per_page);
echo "<br>"; echo "<br>";
for($r=1;$r<=$number_of_pages;$r++)
{
?><?php echo $r." "; ?><?php
}
?>
Related
I currently have three tables. One is housekeeping_employee, second one is housekeeping_benefit, and the third one is the housekeeping_employeebenefits. housekeeping_Employeebenefits is my table where a benefit is assigned/inserted to an employee. Here's my code for displaying the housekeeping_employee in a dropdown, displaying the housekeeping_benefit in checkboxes, and lastly the submit button for the employeebenefits to insert the benefits into the employee.
<?php
if(!isset($_POST['insert']))
{
echo "<br>";
echo "<form method ='POST' action='' >";
$ctr = 0;
$employee = mysqli_query($conn, "SELECT * FROM housekeeping_employee") or DIE("Could not Select");
echo "<select class='indent' name = 'Employee'>";
echo "<option>Select</option>";
while($listEmployee = mysqli_fetch_array($employee))
{
echo "<option value = ".$listEmployee['employeeid'].">".$listEmployee['firstname']."</option>";
}
echo "</select>";
echo "<br><br>";
echo "<div class='indent'>";
$benefits = mysqli_query($conn, "SELECT * FROM housekeeping_benefit")or DIE("SELECT Query not working.");
if(mysqli_num_rows($benefits))
{
while($row = mysqli_fetch_array($benefits))
{
$ctr++;
echo "<h6><input type = 'checkbox' name = 'benefits".$ctr."' value ='".$row['benefitid']."' >".$row['benefitname']." </input></h6> <br>";
if($ctr == 5){
echo"<br>";
$ctr=0;
}
}
echo "<br><input type='submit' class='btn btn-info' name='insert' value='Submit'/>";
}
echo "<input type='hidden' name='ctr' value='".$ctr."'/>";
echo "</form>";
}
else
{
$employeeid = $_POST['Employee'];
for($a = 1; $a <= $_POST['ctr'] ; $a++)
{
if(isset($_POST['benefits'.$a]))
{
$benefitid = $_POST['benefits'.$a];
//echo "INSERT INTO `housekeeping_employeebenefits`(`employeeid`,`benefitid`) VALUES('$employeeid','$benefitid')";
mysqli_query($conn, "INSERT INTO `housekeeping_employeebenefits`(`employeeid`,`benefitid`) VALUES('$employeeid','$benefitid')") or DIE("Insert query is not working");
echo "Employee to Benefits successful!";
}
}
}
?>
I did a join query so I can see the benefits under the employee. Here's my query
SELECT * FROM housekeeping_employee A,housekeeping_benefit B,housekeeping_employeebenefits C where (A.employeeid = A.employeeid and B.benefitid = C.benefitid) and A.employeeid = 2
My friend suggested that I use an onclick which I've never heard or used before so my main question is really far from what I have at the moment but here it is. So from my original code I plan to remove the code that displays all checkboxes of benefits and instead replace it with only displaying the checkboxes of benefits that the employee has. How do I do a trigger that will display the benefit checkboxes under the employee when I choose/click an employee from the dropdown?
EDIT:
If onclick is not what I need, what syntax/command do I need?
Okay, so I'm working on a PHP site, I have descriptions of the product under the image, what I'm need to do is limit the amount of characters on the page and add a click here or.. For the viewers to be directed to that products page to see the full description. FYI very new to PHP, here is what I have so far. So question is do I use PHP or javascript or both and how do I do that ?
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo $product_name . "</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo "<a href='deleteproduct.php'><button>delete</button></a>";
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
using strlen and substr we can achieve this
$length = 150
$x = 'string';
if(strlen($x)<=$length)
{
echo $x;
}
else
{
$y=substr($x,0,$length) . '...';
echo $y;
}
I'm trying to make a program that takes 5 words from a database randomly and inserts them into an array. The page initially loads as desired, but nothing happens after the button is clicked. None of the alerts are ever triggered, so the function must never be entered, but why is beyond me. Also, I get an error saying name isn't a legitimate index (referencing line 13) the first time I try running it on a browser, so advice about that would be great too.
lingo.php:
<?php
session_start();
if (empty($_POST["name"])):
$_SESSION["error"] = "You did not enter a name.";
header("Location: entername.php");
else:
$name = $_POST["name"];
setcookie("name", "$name", time()+3600);
endif;
?>
<html>
<head>
<b>Welcome to Lingo, <?php echo $_COOKIE["name"]; ?></b><br />
<script src = "http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript" language = "javascript">
var arr = [];
function collectWords() {
$.post("getWord.php",
function(data) {
arr[word1] = $(data).find("Word1").text();
alert("function reached");
alert(arr[word1]);
arr[word2] = $(data).find("Word2").text();
alert(arr[word2]);
arr[word3] = $(data).find("Word3").text();
alert(arr[word3]);
arr[word4] = $(data).find("Word4").text();
alert(arr[word4]);
arr[word5] = $(data).find("Word5").text();
alert(arr[word5]);
});
}
</script>
</head>
<body>
<table id = "theTable" border = "1" class = "thetable"> </table>
<input type = "submit" value = "Start" onclick = "collectWords()">
</body>
</html>
getWord.php
<?php
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
if ($db->connect_error):
die ("Could not connect to db " . $db->connect_error);
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word1>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word1>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word2>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word2>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word3>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word3>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word4>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word4>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word5>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word5>";
else:
die ("DB Error");
endif;
?>
You get the error on $_COOKIE["name"]; because said cookie isn't set until you set it. You don't set the cookie until someone has entered their names, so on the first load it will give an error.
http://www.thesitewizard.com/php/set-cookies.shtml
"Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:"
Found under the header: "How to get the contents of a cookie.
Fix this with a shorthand if statement, like so:
<b>Welcome to Lingo,
<?php isset($_COOKIE["name"]) ? $_COOKIE["name"] : $_POST["name"]; //Checks if the cookie is set. If not, uses the $_POST name ?>! </b><br />
I have another question:
Why are your words requested 1 at a time? Why not get all 5 words in 1 query? Also, why send them back as XML data? Since you seem to be handling the data yourself, I would personally recommend a simple loop on the PHP side, returning it as a handy pre-made JSON array.
edit: Also important, PHP does not echo any content automatically. An AJAX call can only receive printed data. You need to echo your results at the end of your php script or you will return nothing
Like so:
$query = "select word from Words order by rand() limit 5";
$result = $db->query($query);
$rows = $result->num_rows;
$array = array();
if ($rows >= 1):
$i = 0;//start the wordcount
//While there are results, loop. (Results are limited to 5, so it won't loop more than 5 times)
while($row = $result->fetch_row()){
$i++;//Put this on top so it starts with "1"
$array["word$i"] = $row[0]; //create the array
}
echo json_encode($array); //Turn array into json and echo it.
else:
die ("DB Error");
endif;
Now, you will also need to change your Javascriptside a tiny bit.
This is how you will access the new array (created by php)
<script type = "text/javascript" language = "javascript">
function collectWords() {
$.post("getWord.php",
function(data) {
alert(data); // show whether you get any data back in the first place. thanks #jDo
var arr = $.parseJSON(data);
alert(arr.word1);
alert(arr.word2);
alert(arr.word3);
alert(arr.word4);
alert(arr.word5);
});
}
</script>
As you can see, this way saves you quite a lot of code and saves you a lot of word replacements
So I have a user page in which I include several tables, one of which uses a pagination script that is handled by javascript (so that I dont have to refresh the page when looking through the pages) now I'm trying to include this on my user.php page but it doesnt seem to work, any help appreciated
User.php page
<?php require 'session.php';
require 'header.php';
require 'includes/database.php';
$userid = $_GET['id'];
$con = mysql_connect($servername, $username, $password);
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname);
//CLIENT INFO TABLE
include 'user/clientinfo.php';
echo "<br>";
// XLRSTATS TABLE
include 'user/xlrstatsinfo.php';
echo "<br>";
//ALIAS TABLE
include 'user/aliases.php';
//IP TABLE
include 'user/ipaliases.php';
//PENALTY TABLE
include 'user/penalties.php';
//PENALTY TABLE
include 'user/userchatlog.php';
?>
userchatlog.php page
<?php
require '../session.php';
?>
<div id='retrieved-data'>
<!--
this is where data will be shown
-->
<img src="../images/ajax-loader.gif" />
</div>
<link rel="stylesheet" type="text/css" href="http://144.76.158.173/ech/includes/css/main.css" />
<script type = "text/javascript" src = "../includes/js/jquery-1.7.1.min.js"></script>
<script type = "text/javascript">
$(function() {
//call the function onload
getdata( 1 );
});
function getdata( pageno ){
var targetURL = '../includes/pagination/userchatlog/search_results.php?page=' + pageno;
$('#retrieved-data').html('<p><img src="../images/ajax-loader.gif" /></p>');
$('#retrieved-data').load( targetURL ).hide().fadeIn('slow');
}
</script>
and my search_results.php
<!-- include style -->
<link rel="stylesheet" type="text/css" href="http://144.76.158.173/ech/includes/css/main.css" />
<?php
//open database
include '../../database.php';
//include our awesome pagination
//class (library)
include 'ps_pagination.php';
//connect to mysql server
$mysqli = new mysqli($servername, $username, $password, $dbname);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
function _ago($tm,$rcs = 0) {
$cur_tm = time(); $dif = $cur_tm-$tm;
$pds = array('second','minute','hour','day','week','month','year','decade');
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
$no = floor($no); if($no <> 1) $pds[$v] .='s ago'; $x=sprintf("%d %s ",$no,$pds[$v]);
if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
return $x;
}
//query all data anyway you want
$sql = "SELECT * FROM chatlog WHERE msg NOT LIKE '%RADIO%' ORDER BY id DESC";
//now, where gonna use our pagination class
//this is a significant part of our pagination
//i will explain the PS_Pagination parameters
//$conn is a variable from our config_open_db.php
//$sql is our sql statement above
//3 is the number of records retrieved per page
//4 is the number of page numbers rendered below
//null - i used null since in dont have any other
//parameters to pass (i.e. param1=valu1¶m2=value2)
//you can use this if you're gonna use this class for search
//results since you will have to pass search keywords
$pager = new PS_Pagination( $mysqli, $sql, 45, 4, null );
//our pagination class will render new
//recordset (search results now are limited
//for pagination)
$rs = $pager->paginate();
//get retrieved rows to check if
//there are retrieved data
$num = $rs->num_rows;
if($num >= 1 ){
//creating our table header
echo "<table id='my-tbl'>";
echo "<tr>";
echo "<th>Time</th>";
echo "<th>Name</th>";
echo "<th>Message</th>";
echo "</tr>";
//looping through the records retrieved
while( $row = $rs->fetch_assoc() ){
$msg=$row['msg'];
$team=$row['client_team'];
$team = str_replace("42","<img src=images/green.png>",$team);
$team = str_replace("3","<img src=images/red.png>",$team);
$team = str_replace("2","<img src=images/blue.png>",$team);
$team = str_replace("1","<img src=images/grey.png>",$team);
$msg = str_replace("^0","</font><font color=black>",$msg);
$msg = str_replace("^1","</font><font color=red>",$msg);
$msg = str_replace("^2","</font><font color=lime>",$msg);
$msg = str_replace("^3","</font><font color=yellow>",$msg);
$msg = str_replace("^4","</font><font color=blue>",$msg);
$msg = str_replace("^5","</font><font color=aqua>",$msg);
$msg = str_replace("^6","</font><font color=#FF00FF>",$msg);
$msg = str_replace("^7","</font><font color=white>",$msg);
$msg = str_replace("^8","</font><font color=white>",$msg);
$msg = str_replace("^9","</font><font color=gray>",$msg);
$name=$row['client_name'];
$name=htmlentities($name);
$time=$row['msg_time'];
echo "<tr class='data-tr' align='center'>";
echo "<td align=center>";
echo _ago($time);
echo "</td>";
echo "<td align=center>";
echo $team;
echo "<a href='http://144.76.158.173/ech/user.php?id=".$row["client_id"]."' > $name </a></td>";
echo "<td align=left> $msg </td>";
echo "</tr>";
}
echo "</table>";
}else{
//if no records found
echo "No records found!";
}
//page-nav class to control
//the appearance of our page
//number navigation
echo "<div class='page-nav' align='center'>";
//display our page number navigation
echo $pager->renderFullNav();
echo "</div>";
?>
Basically, I want to retrieve a certain product after clicking on an element. I'm using AJAX to pass the variable, and PHP to display the SQL query. I will use the product id on a WHERE statement, to retrieve and display the correct product.
Here is part of my code so far:
<html>
<head>
<title>Left Frame</title>
<link href='http://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<link href="stylesheets/main.css" rel="stylesheet" type="text/css">
<script src="javascripts/jquery-1.11.2.js">
</script>
</head>
<body>
<div class="container">
<div id="bottomHalf">
<img id="blank" src="assets/bottom_half.png" style= "z-index: 5" >
<img src="assets/frosen_food.png"
usemap="#Map2"
border="0"
id="frozen"
style="z-index: 0;
visibility:hidden;" >
<map name="Map2">
<area shape="rect" coords="7,95,126,146" alt="Hamburger Patties" href="#" id="hamburgerPatties">
</div>
</div>
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(){
//display something if it succeeds
alert( hamburgerPatties );
}
});
});
</script>
</body>
</html>
Part of my PHP code:
<?php
$product_id =(int)$_GET['variable1'];
$servername = "************";
$username = "************";
$password = "*************";
$dbname = "poti";
$tableName = "products";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM $tableName ";
$result = $conn->query($sql);
// Display all products on the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
}
} else {
echo "0 results";
}
// Display product I clicked on the other frame
if (isset($GET['variable1'])) {
$sql = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = $conn->query($sql);
if ($result) {
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
echo '</tr>';
}
echo '</table>';
}
}
$conn->close();
?>
I'm able to display all the products. But starting from the ifsset statement, the code no long works. I get no error message or anything. How can I solve this? I'm pretty new to PHP.
EDIT: Ok, I managed to get the product I want when I hard code the product id. Now I need to get this variable using javascript.
You have syntax errors in your if statements.
When you're setting if, you should enclose the statement in braces:
instead of if something : do if(something): and then end it with endif; (when using colons :)
// Display product I clicked on the other frame
if (isset($GET['variable1'])):
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result):
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
endif;
endif;
Or, use {} braces instead of colons :
// Display product I clicked on the other frame
if (isset($GET['variable1'])){
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result){
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
}
}
You have syntax error in if block. use {} for if block also use echo instead of pure html tag(table). This error prevents successful state of ajax request. also don't forget to close table.
if ($result)
{
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', $row['product_id'], '</td><td>'; // and others
echo '</tr>';
}
echo '</table>';
}
and the ajax code to display php result instead of test alert would be this:
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(data){
alert(data);
}
});
});
</script>