echo pagenumber html php - php

I am trying to echo pagenumbers in html. Below is the code. It does echo,
but numbers are always on left side of the page. Then I created a div to
center it, it did, but then all numbers are div. When user clicks on
numbers, basically, div gets clicked. I want user to be able to click on
each page number with page numbers at the center of the page.
<html>
<body>
<?php
for ($i = 1; $i <= $total_pages; $i++) { // print links for all pages
echo '<a href="getjobs.php?function_Options[0]='.$q.'& function_Options[1]='.
$q1.'&state_Options[0]='.$qq.'&state_Options[1]='.
$qq1.'&state_Options[2]='.$qq2.'&state_Options[3]='.
$qq3.'&state_Options[4]='.$qq4.'&state_Options[5]='.
$qq5.'&page='.$i.'"';
if ($i==$page) echo " class='curPage'";
echo " style='color: white; font-size: 20pt;'>".$i."</a> ";
};
?>
</body>
</html>

<div class="pageNr">
<?php
for ($i=1; $i<=$total_pages; $i++) { // print links for all pages
echo('<a href="getjobs.php?
function_Options[0]='.$q.'&
function_Options[1]='.$q1.'&
state_Options[0]='.$qq.'&
state_Options[1]='.$qq1.'&
state_Options[2]='.$qq2.'&
state_Options[3]='.$qq3.'&
state_Options[4]='.$qq4.'&
state_Options[5]='.$qq5.'&
page='.$i.'"');
if ($i==$page) echo " class='curPage'";
echo " style='color: white; font-size: 20pt;'>".$i."</a> ";
};
?>
</div>
So you just need to make the width of your div like a couple of pixels and let it float right... this should work.
And just a little tip: best practice is that you don't use inline css...

Related

Make elements in a list clickable (PHP)

I'm currently developing a simple web page that enables the user to: upload an image and a corresponding caption to a DB, let the user view the images and delete them.
I have already accomplished the first two with the following code:
<?php
#include_once("connection.php");
$db = new mysqli("192.168.2.2", "root", "", "proyectoti");
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo "Información de servidor: ";
echo $db->host_info . "\n";
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); #$_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$sql = "INSERT INTO images (image, image_text) VALUES ('{$image}', '{$image_text}')";
// execute query
mysqli_query($db, $sql);
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html>
<head>
<title>Proyecto TI | Sube imágenes</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<h1>Proyecto TI | <a> Interfaz </a></h1>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="image_text"
placeholder="Di algo de esta imagen ^^"></textarea>
</div>
<div>
<button type="submit" name="upload">Publicar</button>
</div>
</form>
</div>
</body>
</html>
It looks like this:
Now, the only part I'm missing is being able to delete an image (basically I only echo each image), how would you suggest for me to accomplish this, to make each item clickable and let's say, pop up a dialog or button to perform an action (delete from DB).
I really don't know much about PHP or CSS/HTML, any help would be much appreciated, Thank you!
Within this loop:
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
Personally I would add an element to click on - like an 'x' or whatever - with a unique data attribute:
https://www.abeautifulsite.net/working-with-html5-data-attributes
You have to add the unique id of the image obviously, so you can let SQL know which row to delete... Like this:
echo "<div class='delete-image' data-id='" . $row['id'] . "'>x</div>';
Then I would link this class to an AJAX call to make an asynchronous request to the server and delete the image without reloading the page. It's not very hard.
An easier solution would be to create a new form in the loop, so you create multiple forms per image, add a hidden field with the image id in the form and make a submit button with the valeu 'delete' or simply 'x'.
The same way you created the check:
if (isset($_POST['upload'])) { ... }
You can create something like this:
if (isset($_POST['delete-image'])) { ... }
You will be carrying the image id value like a normal form input. And you can do whatever you want with it.
I would HIGHLY suggest you to look into how to work with jquery and ajax calls though.
Opening a dialogue and ask the user before he deletes an item will require that you either go another page for deletion or use javascript for this.
In both cases, you should somehow set an identifier for your image in your html-code.
I would suggest you give every image an id
'<img ... id="'.$yourImageId.'">'
or a data-attribute
'<img ... data-identifier="'.$yourImageId.'" >'
with that identifier.
First variant:
...
echo '<a href="/path/to/delete/view/page.php?image=yourImageId">'
echo '<img ... id="'.$yourImageId.'"/>'
echo '</a>'
...
and on this delete-view-page, you just have a form that triggers your delete-code
<form action="/path/to/delete/view/page.php" method="POST">
<input type="hidden" name="id" value="<?php echo $yourImageId ?>">
</form>
<!-- after this, react with $_POST['id'] --> to the id sent to the server side and delete the image in your database -->
The other way is not server side rendered.
You should give your Elements some class like "my-clickable-image".After that, you have a script on your page, that looks something like the following
<script>
/* get your images with querySelectorAll, the . stands for class and after that your name */
var clickables = document.querySelectorAll(".my-clickable-image");
clickables.foreach(function(image){
// say that for each image, when clicked the generated function is called image.addEventListener('click',generateShowDialogueFunc(image.getAttr("id")));
});
// generate a function(!) that reacts to an image being clicked
function generateShowDialogueFunc(imageIdentifier){
// return a function that adds a Pop Up to the page
// the Pop Up has approximately the code of the first options second page
// except that now, it must create and remove elements in javascript
return function createPopUp(){
removePopUp();
var popup = document.createElement("div");
popup.setAttribute("id","deletePopUp");
var deleteForm = document.createElement("form");
deleteForm.setAttr("action","/path/to/file/that/deletes/given/query.php?id="+imageIdentifier);
var deleteContents = '<p> Do you want to delete this image? </p>'
+ '<button type="submit"> yes </button>'
+ '<button onclick="removePopUp()"> no </button>'
deleteForm.innerHTML = deleteContents;
document.body.appendChild()
}
}
// remove the Pop Up that can be used to delete an image from the page
function removePopUp(){
var existingPopUp = document.getElementById("deletePopUp");
if(existingPopUp) document.body.removeChild(existingPopUp);
}
</script>
<!-- just add some styling to make the popup show on top of the page -->
<style>
#deletePopUp{
width: 50vw;
height: 50vh;
position: absolute;
z-index: 1;
padding: 1em;
}
</style>
In this case, you just call the server to delete the image, not to show the delete form.
I would suggest the second one but stack overflow is not made for opinion based answers.
Regarding simple security:
It looks like your users could give titles or texts to images.
try what happens if a user gives a title like <bold>some title</title>
and guess what would happen if the title is <script>window.location.href="google.com"</script>
(XSS * hint hint *)
Regarding code structure:
If you want to do something like web development more often, think about separating your database accessing code, and your logic code from your php page template code, this is called 3 tier architecture and standard for bigger projects but i guess this is really just a first, short prototype or test.

Use php to generate div and select with jquery

I have some jquery question :
First my php code :
<?php
for($C=1; $C <= 9; $C++)
{
echo '<div id="couvert_'.$C.'" style="width:100px;height:30px;float:left;padding-top:10px;padding-left:0px;padding-right:10px;margin:4px 4px 4px 4px;cursor:pointer;text-align:center;background-color:#dfdfdf;">'.$C.'</div>';
}
?>
I generate 9 div element.
I would like to generate jquery script to :
- select one of those div
- change background color of my selected div with #FF7E15
- let the others div with background color #dfdfdf
DO you have an idea ?
Thank you very much.
at the end of your php script use this jquery script:
<script>
//now maybe you want to change the selected div with the mouse?
$("div").click(function(e){
//loop over the divs and set them to the std. color
$("div").each(function(e){
$(this).css("background-color","#dfdfdf");
});
//set the current clicked div to the right color
$(this).css("background-color","#ff7e15");
});
</script>
<script>
jQuery(document).ready(function(){
$('.convert').click(function(){
$(this).css('background-color', '#FF7E15');
});
})
</script>
<?php
for($C=1; $C <= 9; $C++)
{
echo '<div class="convert" id="couvert_'.$C.'" style="width:100px;height:30px;float:left;padding-top:10px;padding-left:0px;padding-right:10px;margin:4px 4px 4px 4px;cursor:pointer;text-align:center;background-color:#dfdfdf;">'.$C.'</div>';
}
?>
Mad answer
PHP:
<?php
for($C=1; $C <= 9; $C++)
{
echo '<div id="couvert_'.$C.'" style="width:100px;height:30px;float:left;padding-top:10px;padding-left:0px;padding-right:10px;margin:4px 4px 4px 4px;cursor:pointer;text-align:center;background-color:#dfdfdf;">'.$C.'</div>';
}
?>
jQuery + PHP:
<?php
$magicElement = 3;
echo "$(\"#couvert_" . $magicElement . "\").css(\"background-color\", \"#FF7E15\")";
?>

PHP: for-loops and if-statement

I am currently studying a beginning PHP programming class and I need some assistance with one assignment I'm trying to solve. The assignment is to create a form where the user can enter a positive integer. Then, use a “for” loop to display that amount of horizontal lines created by the "hr" tag [Hint: <hr size=1 width=50% color='black'>]. Finally, use an if statement to perform “modulus” calculation. When the counter in the “for” loop is an even number set the width of the horizontal line to 50%; otherwise, set the width of the horizontal line to 100%.
Here's the code I have come up with thus far:
<?php
if ($_POST) { // if the form is filled out
$integer = $_POST["pi"];
$i = $integer;
for ($i = 1; $i <= $integer; $i++) {
if ($i % 2) { // modulus operator
echo "<hr size=1 width=50% color='black'>";
} else {
echo "<hr size=1 width=100% color='red'>";
}
}
}
else { // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter a <i>Positive Integer</i>:
<input type="text" name="pi" size=5>
<input type="submit" value="Check"></form></p>
<?php
}
?>
I can't post an image yet, but the sample output should be a 50% black horizontal rule, followed by a 100% red horizontal rule, until the integer entered is reached. In between each hr seems to have some spacing.
This line:
$i = $integer;
...is redundant, as soon as you say for($i = ..., $i will be overwritten. In your case, so it should be. Take that line out to start with.
Second, I think the problem you're having is that your lines aren't showing as black or red. Reason is that color is a font attribute and you should look at this post to find out how to change your color:
Changing the color of an hr element
I suggest using class='black' and class='red' in your PHP and setting classes up in your CSS.
It isn't clear what the problem is. If the issue is that your HR elements have spaces between them, then removing the default margin will help (at least in Firefox, I'm not sure if all browsers use the same rendering rules on HR).
<hr size="1" width=50% color='black' style="margin:0;" />
<hr size="1" width=100% color='red' style="margin:0;" />
The issue is that you are assigning $i equal to the variable $integer, therefore they are the same value.
<?php
if ($_POST)
{ // if the form is filled out
$integer = $_POST["pi"];
for ($i = 1; $i <= $integer; $i++)
{
if ($i % 2 ===0)
{ // modulus operator
echo "<hr size=1 width=50% color='black'>";
}
else
{
echo "<hr size=1 width=100% color='red'>";
}
}
}
else
{ // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter a <i>Positive Integer</i>:
<input type="text" name="pi" size=5>
<input type="submit" value="Check"></form></p>
<?php
}
?>
use this CSS code to formatting all hr elements
<style type="text/css">
hr {margin: 0px auto 0px auto;}
</style>

Creating 5 Star Rating System With PHP , MySQL ,Jquery And Ajax

I've downloaded this tutorial http://megarush.net/5-star-rating-system-with-php-mysql-jquery-and-ajax/ but I'm getting these errors:
Notice: Undefined variable: rat in C:\xampp\htdocs\rating\rating.php on line 37
Notice: Undefined variable: v in C:\xampp\htdocs\rating\rating.php on line 41
<?php
include("settings.php");
connect();
$ids=array(1,2,3);
?>
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<link rel="stylesheet" href="rating.css" />
<script type="text/javascript" src="rating.js"></script>
</head>
<body>
<?php
for($i=0;$i<count($ids);$i++)
{
$rating_tableName = 'ratings';
$id=$ids[$i];
$q="SELECT total_votes, total_value FROM $rating_tableName WHERE id=$id";
$r=mysql_query($q);
if(!$r) echo mysql_error();
while($row=mysql_fetch_array($r))
{
$v=$row['total_votes'];
$tv=$row['total_value'];
$rat=$tv/$v;
}
$j=$i+1;
$id=$ids[$i];
echo'<div class="product">
Rate Item '.$j.'
<div id="rating_'.$id.'" class="ratings">';
for($k=1;$k<6;$k++){
if($rat+0.5>$k)$class="star_".$k." ratings_stars ratings_vote";
else $class="star_".$k." ratings_stars ratings_blank";
echo '<div class="'.$class.'"></div>';
}
echo' <div class="total_votes"><p class="voted"> Rating: <strong>'.#number_format($rat).'</strong>/5 ('.$v. ' vote(s) cast)
</div>
</div></div>';}
?>
</body></html>
$rat and $v are being defined within the scope of your while loop.
If you declare them globally (outside the loop), the rest of your code will recognize them.
$rat = 0;
$v = 1;
while($row=mysql_fetch_array($r))
{
$v=$row['total_votes'];
$tv=$row['total_value'];
$rat=$tv/$v;
}
See here:
http://bgallz.org/988/javascript-php-star-rating-script/
This combines a Javascript code that generated the URL for the different ratings given as well as the change in display for the stars before and after a rating is given.
An overlay DIV is displayed after the rating is given so that no immediate ratings can be given by the same. It also stores the user's IP address with the rating submission to prevent multiple ratings from one user.
This is a simple and easy to use script with just Javascript and PHP for star rating.
The problem is because of scoping of those variables. When you are trying to echo those variables outside the while loop; PHP can not find the varables as they were created (and assigned) inside the loop. To solve this, just assign a blank value to both variables outside too:
if(!$r) echo mysql_error();
$rat = 0;
$v = 1; // In case there are no records.
while($row=mysql_fetch_array($r))
{
$v = $row['total_votes'];
$tv = $row['total_value'];
$rat = $tv/$v;
}
Add this at line at beginning to nide notice error in your code .
error_reporting(E_ALL ^ E_NOTICE);
Most of time notice error do not affect the program.
In case if your votes are not recording then delete your cookies and try to vote from different IP address .This script has a feature to not accept votes from same ip or vistitor to avoid multiple votes by same users on same product.
var cname=document.getElementById(id).className;
var ab=document.getElementById(id+"_hidden").value;
document.getElementById(cname+"rating").innerHTML=ab;
for(var i=ab;i>=1;i--)
{
document.getElementById(cname+i).src="star2.png";
}
var id=parseInt(ab)+1;
for(var j=id;j<=5;j++)
{
document.getElementById(cname+j).src="star1.png";
}
Code from http://talkerscode.com/webtricks/star-rating-system-using-php-and-javascript.php
<style>
.star {
font-size: x-large;
width: 50px;
display: inline-block;
color: gray;
}
.star:last-child {
margin-right: 0;
}
.star:before {
content:'\2605';
}
.star.on {
color: red;
}
.star.half:after {
content:'\2605';
color: red;
position: absolute;
margin-left: -20px;
width: 10px;
overflow: hidden;
}
</style>
<div class="stars">
<?php
$enable = 5.5; //enter how many stars to enable
$max_stars = 6; //enter maximum no.of stars
$star_rate = is_int($enable) ? 1 : 0;
for ($i = 1; $i <= $max_stars; $i++){ ?>
<?php if(round($enable) == $i && !$star_rate) { ?>
<span class="<?php echo 'star half'; ?>"></span>
<?php } elseif(round($enable) >= $i) { ?>
<span class="<?php echo 'star on'; ?>"></span>
<?php } else { ?>
<span class="<?php echo 'star'; ?>"></span>
<?php }
}?>
</div>

Help with foreach loop PHP

Currently producing a Wordpress plugin that allows for multiple image sliders. At the moment, to make sure that the code is valid I am having to load each sliders dynamic styling into the tags. This is fine, however it loads the styling for all the sliders, which can really start to add a lot of code to the pages source if the users uses many image sliders.
So I'm trying to get the styling to only be added to the tags if the slider is actually displayed on the page. Is this possible? This is how I am currently displaying the styling:
function test() {
global $wpdb;
$table_name = $wpdb->prefix . "premiumslider";
$number = $wpdb->get_results("SELECT * FROM $table_name");
foreach ($number as $slider) { ?>
<style type="text/css"><?php if($slider->paginationstyle == 'icons') { ?>
#lofslidecontent<?php echo $slider->id; ?> .lof-navigator li{<?php if($slider- >paginationstyle=='icons'){ ?>background: url(<?php if($slider->paginationoff=='') echo WP_PLUGIN_URL.'/premium-slider/images/pagination.png'; if($slider->paginationoff!='') echo $slider->paginationoff; ?>) 0 0 no-repeat;<?php } ?>}
#lofslidecontent<?php echo $slider->id; ?> .lof-navigator li.active{<?php if($slider->paginationstyle=='icons'){ ?>background: url(<?php if($slider->paginationon=='') echo WP_PLUGIN_URL.'/premium-slider/images/pagination_current.png'; if($slider->paginationon!='') echo $slider->paginationon; ?>) 0 0 no-repeat;<?php } ?>}
<?php } ?>
<?php if($slider->paginationstyle == 'images') { ?>
#lofslidecontent<?php echo $slider->id; ?> .lof-navigator { margin-top: 50px; }
#lofslidecontent<?php echo $slider->id; ?> .lof-navigator li img { border: <?php echo $slider->imgborder; ?>px solid #<?php echo $slider->imgcolour; ?>; }
#lofslidecontent<?php echo $slider->id; ?> .lof-navigator li.active img { border: <?php echo $slider->imgborder; ?>px solid #<?php echo $slider->imghover; ?>; }
#lofslidecontent<?php echo $slider->id; ?> .lof-navigator li.active img:hover { border: <?php echo $slider->imgborder; ?>px solid #<?php echo $slider->imghover; ?>; }
<?php } ?></style><?php
}
}
How can I achieve this?
To display the above code I use:
add_action('wp_head','test');
And to display the slider ($id being the id of that particular slider; 1, 2, 3, etc):
premium_slider($id);
This is sort of a complicated question. First of all, I disparage you for using a global variable, especially a DB resource. I'm also unclear as to why you need to echo the styles directly in this way.
Now to help you:
The only way to really solve this that I can see is if you have all of the styles stored somewhere, such as a DB, a config file, or any such thing per style. You must know the styles beforehand because you are hard coding them here. So just cycle through and if the ID of your slider matches its style, print the style. If you stored all of the styles in a big array in another php file hashed with the ID of the slider, this would be simple.
How do you determine which sliders appear on the page? Effectively you would need to alter your query to be the same as the one which actually loads the sliders, that way the CSS would only be loaded to display the same sliders.
$table_name = $wpdb->prefix . "premiumslider";
$number = $wpdb->get_results("SELECT * FROM $table_name WHERE category = 'cars'");
This would only load the elements into the foreach array that are displayed on that particular page.

Categories