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;
Related
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);
?>
In have an array that looks like this
$content = [["4","1",1,9],["1","3",3,1],["3","4",4,7]]
I would like to insert those values into the database, this is what i've had tried
if(is_array($content)) {
foreach ($content as $c) {
list($job_id, $job_bay_id, $row, $col) = explode(',', $c);
try {
update_calendar($job_id, $job_bay_id, $row, $col);
} catch (Exception $ex) {
$_SESSION["errorMsg"] = $ex->getMessage();
$_SESSION["errorType"] = "danger";
}
}
}
function update_calendar($job_id, $job_bay_id, $row, $col){
global $DB;
$sql1 = "UPDATE " . TBL_CALENDAR . " SET `job_bay_id` = :job_bay_id, `tbl_row` = :row, `tbl_col` = :col WHERE `job_id` = :job_id ";
try {
$stmt = $DB->prepare($sql1);
$stmt->bindValue(":job_bay_id", $job_bay_id);
$stmt->bindValue(":row", $row);
$stmt->bindValue(":col", $col);
$stmt->bindValue(":job_id", $job_id);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
}
How come autocomplete doesnt work when I got json data that has items in it? I can se that it is becoming a list, but it is not filling with names.
Example of my json data: http://nettport.com/no/stram/search.php?term=e
<script>
$(function() {
$( "#inp_meal_a_0" ).autocomplete({
source: 'search.php'
});
$('#inp_meal_a_0').on('autocompleteselect', function (e, ui) {
var val = $('#inp_size_a_0').val();
var energy = ui.item.energy;
var proteins = ui.item.proteins;
var carbohydrates = ui.item.carbohydrates;
var fat = ui.item.fat;
$("#inp_energy_a_0").val((energy*val)/100);
$("#inp_proteins_a_0").val((proteins*val)/100);
$("#inp_carbs_a_0").val((carbohydrates*val)/100);
$("#inp_fat_a_0").val((fat*val)/100);
});
});
</script>
Search.php
<?php
header('Content-type: text/html; charset=windows-1252;');
// Make a MySQL Connection
$host = $_SERVER['HTTP_HOST'];
if($host == "127.1.1.0"){
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("n") or die(mysql_error());
}
// Quote smart
function quote_smart($value){
// Stripslashes
if (get_magic_quotes_gpc() && !is_null($value) ) {
$value = stripslashes($value);
}
//Change decimal values from , to . if applicable
if( is_numeric($value) && strpos($value,',') !== false ){
$value = str_replace(',','.',$value);
}
if( is_null($value) ){
$value = 'NULL';
}
// Quote if not integer or null
elseif (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
if(isset($_GET['term']) && $_GET['term'] != ''){
$term = $_GET['term'];
$term = strip_tags(stripslashes($term));
$term = trim($term);
$term = strtolower($term);
$term = $term . "%";
$part_mysql = quote_smart($term);
//get matched data from skills table
$x = 0;
$query = "SELECT cc_id, cc_food_name, cc_manufactor_name, cc_serving_size, cc_serving_mesurment, cc_energy, cc_proteins, cc_carbohydrates, cc_fat FROM stram_calorie_calculation WHERE cc_food_name LIKE $part_mysql";
$r = mysql_query($query);
while ($row = mysql_fetch_array($r, MYSQL_NUM)) {
$get_cc_id = $row[0];
$get_cc_food_name = $row[1];
$get_cc_manufactor_name = $row[2];
$get_cc_serving_size = $row[3];
$get_cc_serving_mesurment = $row[4];
$get_cc_energy = $row[5];
$get_cc_proteins = $row[6];
$get_cc_carbohydrates = $row[7];
$get_cc_fat = $row[8];
if($get_cc_food_name == ""){
$result = mysql_query("DELETE FROM stram_calorie_calculation WHERE cc_id='$get_cc_id'") or die(mysql_error());
}
$data[$x] = array('food_name' => $get_cc_food_name, 'energy' => $get_cc_energy, 'proteins' => $get_cc_proteins, 'carbohydrates' => $get_cc_carbohydrates, 'fat' => $get_cc_fat);
//$data[$x] = $get_cc_food_name;
$x++;
}
//return json data
echo json_encode($data);
}
?>
My problem now when I click on the picture on my page, for the first time it will display. But for the second time it will display fail. This process will start by sending the data to ajax, then ajax(prosess.js) will send it to the php page(process1.php).
When I remove the code in blockquote ($query = "SELECT ...") it will run, but if not, it will display fail.
process1.php
<?php
include 'session.php';
include 'connection.php';
if(isset($_POST['dataS'])) {
$table = $_POST['table'];
$concat = "";
$serial = $_POST['dataS'];
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if($row) {
$prodName = $row['prodName'];
$quanProd = 1;
$priceProd = $_POST['total'] + $row['salePrice'];
if($table == "") {
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
}
else{
$DOM = new DOMDocument;
$DOM->loadHTML($table);
$items = $DOM->getElementsByTagName('tr');
$check = 0;
$check_one = 0;
$y=0;
function tdrows($elements,$check,$serial,$prodName,$y) {
$quantity="";
$item = "";
$price = "";
$delete = "";
$x = 0;
foreach($elements as $element) {
if($x == 0)
$delete = $element->nodeValue;
else if($x == 1)
$item = $element->nodeValue;
else if($x == 2)
$quantity = $element->nodeValue;
else if($x == 3)
$price = $element->nodeValue;
$x++;
}
**$query = 'SELECT prodName FROM product WHERE prodName = "$item"';
$search = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($search);
$s = $row['prodName'];**
if($prodName == $s) {
$quantity++;
$check = 1;
}
else {
$check = 0;
}
return $check;
}
foreach ($items as $node) {
$check = tdrows($node->childNodes,$check,$serial,$prodName,$y);
$y++;
}
}
$priceProd = number_format((float)$priceProd, 2, '.', '');
echo json_encode (
array ( //this array is used to send the data back to ajax.
"success" => "1",
"concat" => $concat,
"quantity" => $quanProd,
"price" => $priceProd,
)
);
}
else {
echo json_encode (
array ( //this array is used to send the data back to ajax.
"success" => "0",
)
);
}
}
?>
process.js
$(document).ready(
function() {
$("body").on("click","#product .add",
function(e) {
var total = document.getElementById("total").value;
var table = document.getElementById('table-list').innerHTML;
table = (table.trim) ? table.trim() : table.replace(/^\s+/,'');
var serial = $(this).attr('id');
var totalQ = document.getElementById("totalQ").value;
if(total == "")
total = 0;
else
total = parseFloat(total);
if(totalQ == "")
totalQ = 0;
else
totalQ = parseInt(totalQ);
var dataS = serial;
e.preventDefault();
$.ajax({
type : "POST",
url : "process1.php",
crossDomain: true,
data : {dataS : dataS, table : table, total : total},
dataType : 'json',
})
.done(function(html) {
if(html.success == 1) {
console.log('done: %o', html);
$("#table-list").html(html.concat).show();
document.getElementById('totalQuantity').innerHTML = html.quantity;
document.getElementById("total").value = html.price;
document.getElementById("payment").value = html.price;
document.getElementById('totalQ').value = html.quantity;
document.getElementById('title').innerHTML = html.price;
document.getElementById('input').value='';
$("#input").focus();
}
else {
alert("Wrong serial number!");
document.getElementById('input').value='';
$("#input").focus();
}
})
.fail(function(html) {
console.info('fail: %o', html);
alert("fail");
});
return false;
});
});
connection.php
<?php
$conn = mysqli_connect('localhost','root','','rds');
?>
your query is wrong:try this
$query = "SELECT prodName FROM product WHERE prodName = '".$item."'";
According to your pictures, your problem is that your database connection isn't correct. When you execute the first request it won't do any database interaction (because off the blocknotes). The second request you will send table data, which will perform a query. So the first request will succeed, while the second request will give you an error on your mysqli ($conn) object.
if($table == "") {
//Database interaction
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
}
else{
//No database interaction because of the blocknotes
$DOM = new DOMDocument;
$DOM->loadHTML($table);
$items = $DOM->getElementsByTagName('tr');
$check = 0;
$check_one = 0;
$y=0;
function tdrows($elements,$check,$serial,$prodName,$y) {
$quantity="";
$item = "";
$price = "";
$delete = "";
$x = 0;
foreach($elements as $element) {
if($x == 0)
$delete = $element->nodeValue;
else if($x == 1)
$item = $element->nodeValue;
else if($x == 2)
$quantity = $element->nodeValue;
else if($x == 3)
$price = $element->nodeValue;
$x++;
}
**$query = 'SELECT prodName FROM product WHERE prodName = "$item"';
$search = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($search);
$s = $row['prodName'];**
if($prodName == $s) {
$quantity++;
$check = 1;
}
else {
$check = 0;
}
return $check;
}
foreach ($items as $node) {
$check = tdrows($node->childNodes,$check,$serial,$prodName,$y);
$y++;
}
}
Check your the username, password and database name. I'm pretty sure you used something wrong here. As mentioned in your connection.php file you don't use a password. Are you sure the user root doens't have a password? Can you access the database with a MySQL administration tool like phpMyAdmin?
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;