Need average value PHP, Jquery, Ajax - javascript

I've made a star rating system, using PHP, and Jquery. After i have stored my votes in a database im trying to print the average rate. The problem is the average value that gets printed its for all the items that im rating, not just the specifik one that im rating
This is my jquery code:
function rate(id, vote) {
console.log(id, vote);
$.post("rated.php",
{ id: id, vote: vote }, function(data){
console.log(data);
$( ".totalrating") .html( data );
});
};
And this is my php:
$sql = "UPDATE images
SET votes = votes+1, tot_rating = tot_rating+$vote
WHERE id ='$id' ";
$result = mysqli_query($conn, $sql) or die("Fel vid SQL query");
$sql2 = "SELECT * from images WHERE id=$id";
$result1 = mysqli_query($conn, $sql2) or die ("Fel vid SQL query");
while($row = mysqli_fetch_array($result1)) {
$votes = $row['votes'];
}
$sql3 = "SELECT * from images WHERE id=$id";
$result2 = mysqli_query($conn, $sql3) or die ("Fel vid SQL query");
while($row = mysqli_fetch_array($result2)) {
$sum = $row['tot_rating'];
}
$avg = $sum / $votes;
$avg1decimals = number_format($avg, 1);
echo $avg1decimals;
} else {
}

Try a single select query:
$sql = "UPDATE images
SET votes = votes+1, tot_rating = tot_rating+$vote
WHERE id ='$id' ";
$result = mysqli_query($conn, $sql) or die("Fel vid SQL query");
$sql2 = "SELECT * from images WHERE id=$id";
$result1 = mysqli_query($conn, $sql2) or die ("Fel vid SQL query");
while($row = mysqli_fetch_array($result1)) {
$avg = $row['tot_rating'] / $row['votes'];
$avg1decimals = number_format($avg, 1);
echo $avg1decimals;
}

Try this one : Make sure ID is primary key in your table
$sql = "UPDATE images
SET votes = votes+1, tot_rating = tot_rating+".$vote."
WHERE id =".$id;
$result = mysqli_query($conn, $sql) or die("Fel vid SQL query");
$sql = "SELECT * from images WHERE id=".$id."Limit 1";
$result = mysqli_query($conn, $sql2) or die ("Fel vid SQL query");
while($row = mysqli_fetch_array($result)) {
$votes = $row['votes'];
$sum = $row['tot_rating'];
}
$avg = $sum / $votes;
$avg1decimals = number_format($avg, 1);
echo $avg1decimals;

Related

Populate the department select with the current value in the Edit Employee Form

I need to do the following to finish off my project and as im just learning but need bit of guidance to do the following:
it seems im not populating the department select with the current value in the 'edit employee form', ive been told if i use the getPersonnel.php file it returns the JSON to populate the department select, then all i need to do is set the value of the select to the departmentID value of the employee.
I also know and im going to change my php code to prepared statements to avoid sql injection.
this is my code below:
function updateEditEmployeeModal(employee) {
$.ajax({
url: './php/getPersonnel.php',
type: 'POST',
datatype: 'json',
data: {employeeId: employee.id},
success:function(result){
// console.log(result);
$('#editEmployeeId').html(result.data.personnel[0].id);
$('#editEmployeeFirstNameInput').val(`${result.data.personnel[0].firstName}`);
$('#editEmployeeLastNameInput').val(`${result.data.personnel[0].lastName}`);
$('#editEmployeePositionInput').val(result.data.personnel[0].jobTitle);
$('#editEmployeeEmailInput').val(result.data.personnel[0].email);
$("#editEmployeeDepartmentSelect").val(result.data.personnel[0].departmentId).change();
},
error: function(err){
console.log(err);
}
});
and getPersonnel.php file ::
<?php
// example use from browser
// http://localhost/companydirectory/libs/php/getPersonnel.php?id=1
// remove next two lines for production
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true);
include("config.php");
header('Content-Type: application/json; charset=UTF-8');
$conn = new mysqli($cd_host, $cd_user, $cd_password, $cd_dbname, $cd_port, $cd_socket);
if (mysqli_connect_errno()) {
$output['status']['code'] = "300";
$output['status']['name'] = "failure";
$output['status']['description'] = "database unavailable";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
exit;
}
// first query
$employeeId = $_REQUEST['employeeId'];
$query = $query = "SELECT p.id, p.lastName, p.firstName, p.jobTitle, p.email, p.departmentID as departmentId, d.name as department, l.name as location FROM personnel p LEFT JOIN department d ON (d.id = p.departmentID) LEFT JOIN location l ON (l.id = d.locationID) WHERE p.id = '$employeeId';";
$result = $conn->query($query);
if (!$result) {
$output['status']['code'] = "400";
$output['status']['name'] = "executed";
$output['status']['description'] = "query failed";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
exit;
}
$personnel = [];
while ($row = mysqli_fetch_assoc($result)) {
array_push($personnel, $row);
}
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
$output['data']['personnel'] = $personnel;
mysqli_close($conn);
echo json_encode($output);
?>

How to json encode Specific Key value using PHP?

I have tried this code but receiving error.
$queryfetch = 'select * from table';
$result = mysqli_query($connection, $queryfetch);
$row = mysqli_fetch_assoc($result);
$data = [];
foreach($row as $key) {
$data[] = [
'first_name' => $key['first_name'],
'last_name' => $key['last_name']
];
}
echo json_encode($data);
How can I json encode specific keys using php ?
I have solved..
$queryfetch = 'select * from table';
$result = mysqli_query($connection, $queryfetch);
$row = mysqli_fetch_assoc($result);
$data[] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name']
);
echo json_encode($data);
This code is working very well..

I want to display the following data in table

I want to display the following data in a table.
I have tried fetching data from database but only one column is visible
# AJAX CODE
$.ajax({
url:'process/getState.php',
method:'GET',
success:function(response){
res = JSON.parse(response);
console.log(res);
$.each(res,function(k,v){
var t = $('.template > table > tbody > tr').clone();
t.find('.state').html(v.state);
t.find('.count').html(v.count);
$('#tbody').append(t);
console.log(v);
});
}
})
# PROCESS FILE
<?php
include('connection.php');
$conn = connection();
$sql = "SELECT * FROM statedistribution";
$result = $conn->query($sql);
$state = [];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($state,$row);
}
die(json_encode($state));
} else {
echo "0 results";
}
$conn->close();
?>
I am only getting the data in the state column but the count column is turning out to be blank
You are seeing one column or row because your $state is not declared properly as an array
Simply edit your process file to look like this:
include('connection.php');
$conn = connection();
$sql = "SELECT * FROM statedistribution";
$result = $conn->query($sql) or die ("Error :".mysql_error());
$state = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$state[] = $row;
}
$output = json_encode($state);
} else $output = "0 results";
$conn->close();
echo $output;

difficulties in registering and login

Here is the code:
include_once('class.database.php');
class ManageUsers{
public $link;
function __construct(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link;
}
function registerUsers($password, $ip_address, $date, $time, $username, $email, $uname){
$query = $this->link->prepare("INSERT INTO users (password,ip_address,date,time,username, email, uname) VALUES(?,?,?,?,?,?,?)");
$values = array ($password, $ip_address, $date, $time, $username, $email, $uname);
$query->execute($values);
$count = $query->rowCount();
return $count;
}
function LoginUsers($username, $password){
$query = $this->link->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$rowCount = $query->rowCount();
return $rowCount;
}
function GetUserInfo($username){
$query = $this->link->query("SELECT * FROM users WHERE username = '$username'");
$rowCount = $query->rowCount();
if($rowCount ==1)
{
$result = $query->fetchAll();
return $result;
}
else
{
return $rowCount;
}
}
}
and it is showing me this error
Fatal error: Call to a member function query() on a non-object in
C:\wamp\www\timetable\class.ManageUsers.php on line 22

Ajax call JS + PHP not working

Chrome console error:
POST http://******************** 500 (Internal Server Error)
JS
$.ajax({
method: "POST",
url:"ajax.php",
data: {
x: x,
y: y
},
success:function(data){...}
});
PHP
<?php
date_default_timezone_set('Europe/Madrid');
$link = mysql_connect("*******", "*******", "******");
mysql_select_db("******") or die ("no database");
$name = $_POST['x'];
$score = $_POST['y'];
// Get the current date
$current_date = date('d-m-Y H:i:s');
$sqlCommand = "INSERT INTO hungry_bird (date_played, name, score)
VALUES('$current_date ', '$name', '$score')";
$results = mysql_query($sqlCommand) or die (mysql_error());
mysql_close($link);
?>
Any idea what could be the problem? Thanks.
$link = mysqli_connect("*******", "*******", "******");
mysqli_select_db($link, "******") or die ("no database");
$name = $_POST['x'];
$score = $_POST['y'];
$sqlCommand = "INSERT INTO hungry_bird (date_played, name, score)
VALUES('CURDATE()', '$name', '$score')";
$results = mysqli_query($link, $sqlCommand) or die (mysqli_error($link));
mysqli_close($link);

Categories