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

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>

Related

How to have data allow decimals

I made a program that lets 6 grades be entered into a form, and then calculates the letter grade and the average. The only problem I'm having is that I can't figure out how to get the form to accept decimals. I tried changing my filter_input statement to sanitize floats, but that doesn't seem to fix the problem. Any thoughts would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grades</title>
<link rel="stylesheet" href="bootstrap.min.css">
<script>
window.onload = () => {
document.getElementById('quiz1').focus();
document.getElementById('quiz1').select();
}
</script>
<style>
input[type="text"] {width: 4em !important; text-align: right; margin-left: .5em; }
ul { list-style-type: none; padding-left: 0; }
</style>
</head>
<body>
<div class="container">
<div class="col-lg-6 mx-auto text-center">
<h1>Enter Quiz Grades</h1>
<form action="." method="post">
<?php
// declare an array to store bowling scores
$quizScores = array();
// declare a variable to be used for the natural counting of the number of games
$numberOfScores = 6;
// declare a variable to be used for array elements - subtract 1 since array elements start at 0
$gamesArrayElements = $numberOfScores - 1;
for ($i = 0; $i <= $gamesArrayElements; $i++){
$quizNumber = $i + 1;
// load values from POST into array elements
if (strlen($_POST['quiz' . $quizNumber]) > 0){
$quizScores[$i] = filter_input(INPUT_POST, 'quiz' . $quizNumber, FILTER_SANITIZE_NUMBER_FLOAT);
}
echo "<div class='form-group form-inline justify-content-center'>\n";
echo "<label for='quiz$quizNumber'>Quiz $quizNumber: </label>\n";
echo "<input type='text' class='form-control' name='quiz$quizNumber' id='quiz$quizNumber' value='$quizScores[$i]'>%\n";
echo "</div>\n";
}
?>
<div class="form-group">
<input type="submit" class="btn btn-secondary" value="Find Average of <?php echo $numberOfScores; ?> Highest Quiz Grades">
Clear
</div>
</form>
<?php
if (count($quizScores) === $numberOfScores){
$total = 0;
echo "<h2>Scores:</h2>\n";
echo "<ul>\n";
// for loop to print array elements and add each score to the total
for ($i = 0; $i <= $gamesArrayElements; $i++){
echo "<li>$quizScores[$i] " . getLetterGrade($quizScores[$i]) . "</li>\n";
$total += $quizScores[$i];
}
echo "</ul>\n";
$average = $total / $numberOfScores;
echo "<h2>Average Score:</h2>\n";
echo "<p>" . number_format($average, 1, .2) . " - " . getLetterGrade($average) . "</p>\n";
} else {
if(count($quizScores) > 0) {
echo "<h2 class='text-danger'>All textboxes should contain grades.</h2>\n";
}
}
?>
</div>
</div>
</body>
</html> ```
I changed number_format($average, 1, .2) to number_format($average, 1) and then I do get the average rounded to one decimal. I also removed the getLetterGrade() function because it is not defined in your code. Finally I change the form action to "", instead of ".", because it didn't work in my test environment.
Perhaps you need to switch on error reporting in PHP? That way you can see what's wrong with your code.

Place <a> elements inside two different divs

I have this structure on my page:
*{
margin: 0px;
}
.div1{
width: 1000px;
background-color: grey;
overflow: hidden;
}
.div2{
width: 300px;
background-color: orange;
height: 500px
}
.div3{
width: 300px;
background-color: orange;
height: 500px;
}
.float_left{
float: left;
}
.float_right{
float: right;
}
<div class="div1">
<div class="div2 float_left">
</div>
<div class="div3 float_right">
</div>
</div>
And inside the two orange container's I want to put some smaller divs, but I read the data from a database. The first row should be in div1, the second in div2, the third in div1 and so on.
$sql = "SELECT * FROM question ORDER BY question_id DESC";
$result = mysqli_query($db,$sql);
while($row = mysqli_fetch_assoc($result)){
}
But how can I do something like that? Can I open a div container closed container to place a div container inside the container?
You should really read and try by yourself, this is pretty basic question.
There are many ways, here is one of them.
Declare 2 variables to store the results for Div1 and Div2.
Declare a count variable and use the odd and even property to decide who turn is it to store the results.
Output the results.
PHP:
$sql = "SELECT * FROM question ORDER BY question_id DESC";
$result = mysqli_query($db,$sql);
$resultsForDiv1 = "";
$resultsForDiv2 = "";
$count = 0;
while($row = mysqli_fetch_assoc($result)){
if ($count%2 == 0) {
$resultsForDiv1 .= $row[0]; // You should change it to whatever data you need from $row.
}
else {
$resultsForDiv2 .= $row[0]; // You should change it to whatever data you need from $row.
}
$count++;
}
Html:
<div class="div1">
<div class="div2 float_left">
<?php echo $resultsForDiv1; ?>
</div>
<div class="div3 float_right">
<?php echo $resultsForDiv2; ?>
</div>
</div>
What you should do is store the data from the $row variable into new variables which you can then output in the two columns. Like this:
<?php
$sql = "SELECT * FROM question ORDER BY question_id DESC";
$result = mysqli_query($db, $sql);
// Use this to toggle column on the sql results
$left_right = true;
while ($row = mysqli_fetch_assoc($result)) {
if ($left_right) {
// Add to left column variable
// [some code to add the data from $row to $left_column_content]
} else {
// Add to right column variable
// [some code to add the data from $row to $right_column_content]
}
// Switch columns by inverting the boolean from true to false, false to true
$left_right = !$left_right;
}
?>
<div class="div1">
<div class="div2 float_left">
<?php echo $left_column_content; ?>
</div>
<div class="div3 float_right">
<?php echo right_column_content; ?>
</div>
</div>

How do I make a bar chart in CSS using PHP variables?

I have an array of float values in PHP and I want to turn the array into a bar chart using CSS. Each float value represents a percentage, so if a value is 50.0 then the bar should be 50% of a certain height. I am new to CSS, so I was wondering if anyone could show me how I would go about doing this.
I believe it should look something like this. I doubt that this code would work, but it's an example.
<?php
$values = array(50.0, 20.0, 30.0, 45.0); //This is the array of percentage values
?>
<style>
<?php
for ($i = 0; $i < count($values); $i++) //Create a new bar for each value
{?>
#bar
{
height: <?php 300 * ($values[$i] / 100.0); ?> px; //Specify the height of each bar
width: 30px;
}
<?php
}?>
</style>
Edit:
I've added the code suggested by Tom, but my web page currently produces no bars. Here is the full code for my PHP file. Why does it not produce any CSS content?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Visualisation result</title>
<style>
.bar
{
color: #00ff21;
width: 30px;
}
</style>
</head>
<body>
<?php
$values = array(50.0, 20.0, 30.0, 45.0);
for ($i = 0; $i < count($values); $i++)
{
$currentHeight = 300 * $values[$i] / 100.0; ?>
<div class="bar" style="height: <?php echo($currentHeight); ?> "></div>
<?php
}
?>
</body>
</html>
Your approach won't work, as you will be writing out several different rules for the same selector. It is invalid in HTML to have multiple values with the same ID "bar" anyway.
I guess you could do something like this:
.bar {
width: 30px;
}
<?php
for ($i = 0; $i < count($values); $i++) { ?>
<div class="bar" style="height:<?= 300 * $values[$i] / 100.0 ?>"></div>
<?php
} ?>
This generates the elements using the loop, setting their height using the style attribute. I have used the shorthand <?= instead of <?php echo (you weren't doing either in your question).

How to load values to page while scrolling the page

I have a table named "User" with more than 3k rows in MySql database.I want to fetch the database while scrolling the page(As like Facebook news feeds). I surfed for a long time but I can't get it. hoping positive response as soon as possible.
thank you!
If I understood what did you mean:
Database Table
CREATE TABLE messages(
mes_id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT);
load_data.php
When we are scrolling down a webpage, the script($(window).scroll) finds that you are at the bottom and calls the last_msg_funtion(). Take a look at $.post("") eg: $.post("load_data.php?action=get&last_msg_id=35")
<?php
include('config.php');
$last_msg_id=$_GET['last_msg_id'];
$action=$_GET['action'];
if($action <> "get")
{
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function last_msg_funtion()
{
var ID=$(".message_box:last").attr("id");
$('div#last_msg_loader').html('<img src="bigLoader.gif">');
$.post("load_data.php?action=get&last_msg_id="+ID,
function(data){
if (data != "") {
$(".message_box:last").after(data);
}
$('div#last_msg_loader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_msg_funtion();
}
});
});
</script>
</head>
<body>
<?php
include('load_first.php'); //Include load_first.php
?>
<div id="last_msg_loader"></div>
</body>
</html>
<?php
}
else
{
include('load_second.php'); //include load_second.php
}
?>
load_first.php
Contains PHP code to load 20 rows form the message table.
<?php
$sql=mysql_query("SELECT * FROM messages ORDER BY mes_id DESC LIMIT 20");
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box" >
<?php echo $msg; ?>
</div>
<?php
}
?>
load_second.php
Contains PHP code to load 5 rows less than last_msg_id form the message table.
<?php
$last_msg_id=$_GET['last_msg_id'];
$sql=mysql_query("SELECT * FROM messages WHERE mes_id < '$last_msg_id' ORDER BY mes_id DESC LIMIT 5");
$last_msg_id="";
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box" >
<?php echo $msg;
?>
</div>
<?php
}
?>
CSS
body
{
font-family:'Georgia',Times New Roman, Times, serif;
font-size:18px;
}
.message_box
{
height:60px;
width:600px;
border:dashed 1px #48B1D9;
padding:5px ;
}
#last_msg_loader
{
text-align: right;
width: 920px;
margin: -125px auto 0 auto;
}
.number
{
float:right;
background-color:#48B1D9;
color:#000;
font-weight:bold;
}
Take a look at live demo and scroll down.
Regards,
Ivan
Check out http://jscroll.com/ or just google for "jQuery load content while scrolling" or "jQuery infinite scroll" for other alternatives.

Assign unique ID to div as created and then reference with jquery

I am brand new to php and a beginner with jQuery. I have a php page that is populated with data from a mySQL table. What I am trying to achieve is for the h3 that contains "View Job" to have a unique id assigned to it, as well as the div that prints out the job description. Then, I would like to reference these with jQuery so that if someone clicks View Job, only the description for that job will show. I hope this makes sense.
I tried this with classes and of course all the job descriptions revealed themselves when any View Job was clicked.
I tried the solution here, but this ended up with 36 "View Job" links on my page, and I need to assign the unique ID to the h3 and div as they are created.
I am open to suggestions for another way to achieve what I'm looking for - basically to hide/collapse each description as the user clicks on View Job for each job.
here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("div#job-details").css("display" , "none");
$("h3#view-job").click(function() {
$("div#job-details").css("display" , "block");
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs")
or die(mysql_error());
?>
<div id="job-container">
<?php
Print "";
while($info = mysql_fetch_array( $data ))
{
Print "<div class='job-post'>";
Print "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
Print "<h3 id='view-job'>View Job:</h3> <div id='job-details'>".$info['jobdesc'] . " </div>";
Print "</div>";
}
?>
</div><!--//END job-container-->
Assign the classNames instead of id's
Then use the this context to select your div which will only search for the one in the context and not all the divs
$("h3.view-job").on('click',function() {
$(this).next("div.job-details").css("display" , "block");
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-details{display:none;}
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
// Please hide this class on CSS
// $("div.job-details").css("display" , "none");
$("h3.view-job").click(function() {
// you ned to use this keyword
// it is very important when you use javascript or jquery
// this keyword only pick element on which you click
$(this).parent().find(".job-details").show();
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs")
or die(mysql_error());
?>
<div id="job-container">
<?php
// First of all Please use echo instead of Print
echo "";
while($info = mysql_fetch_array( $data ))
{
echo "<div class='job-post'>";
echo "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
// you can't use id multiple time in a same page so instead of id use Class
// if you want to use id then you have to generate uniq id
// check below I generate id --> I don't know your database field that's why I used jobId
echo "<h3 class='view-job' id='job".$info['jobId']."'>View Job:</h3> <div class='job-details'>".$info['jobdesc'] . " </div>";
echo "</div>";
}
?>
</div><!--//END job-container-->
This should do what you want (tested okay). Just replace your mysql login info and the example should work.
I completed your job-details div (it was missing the data from php), but what you were really looking for is the jQuery code.
When an <h3> tag whose id begins with the characters view-job is clicked, the jQuery click event handler will:
re-hide all divs whose id starts with the chars job-details
display the next div in the DOM tree
CODE:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("div[id^='job-details']").css("display" , "none");
$('h3[id^="view-job"]').click(function() {
$("div[id^='job-details']").hide(500);
$(this).next('div').show(500);
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs") or die(mysql_error());
?>
<div id="job-container">
<?php
echo "<br>";
while($info = mysql_fetch_assoc( $data )) {
echo "<div class='job-post'>";
echo "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
echo "<h3>View Job:</h3> <div id='job-details'>".$info['jobdetails']."</div>";
echo "</div>";
}
?>
</div><!--//END job-container-->

Categories