PHP get URL value in mysql SELECT - javascript

in my current project I want to show statistics in a pie chart with chart.js, but they are different for each team on my page.
I tried to give the WHERE value in the Select in playerOne.php via the URL, but it doesn't seem to work because this PHP file is triggered by a JS function.
I have passed the team_id on the URL via isset get, but this doesn't seem to work.
How can I pass the team_id value on the URL to the query?
playerOne.php
if(isset($_GET['team_id'])) {
$team_id = $_GET['team_id'];
}
$query = "SELECT * FROM user WHERE team_id = 7 LIMIT 1";
$select_team = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($select_team);
$user_id = $row['user_id'];
$query = "SELECT SUM(game_stats.match_stats_kills) AS Kills, SUM(game_stats.match_stats_deaths) AS Deaths FROM game_stats WHERE game_stats.user_id = $user_id";
$select_kd = mysqli_query($connection, $query);
$data = array();
foreach($select_kd as $row) {
$data[] = $row;
}
mysqli_close($connection);
echo json_encode($data);
stats.js
$(document).ready(function() {
showData();
});
function showData() {
{
($.post("includes/stats/playerOne.php",
function(data) {
var kills = [];
var deaths = [];
for(var i in data) {
kills.push(data[i].Kills)
deaths.push(data[i].Deaths);
}
var pieChartData = {
labels: [
'Kills', 'Deaths'
],
datasets: [
{
backgroundColor: ['#f56954', '#00c0ef'],
data: [kills, deaths]
}
]
};
var pieChartTarget = $('#playerKD').get(0).getContext('2d');
var pieChart = new Chart(pieChartTarget, {
type: 'pie',
data: pieChartData
});
}));
}
}
URL
http://localhost/r6team/team/team.php?team=stats&team_id=7

In your JS, you need to send a GET request and leave room for the ID to be dynamic.
stats.js should look like this:
$(document).ready(function() {
showData(7);
});
function showData(teamId) {
{
($.get("includes/stats/playerOne.php?team_id=" + teamId,
function(data) {
var kills = [];
var deaths = [];
for(var i in data) {
kills.push(data[i].Kills)
deaths.push(data[i].Deaths);
}
var pieChartData = {
labels: [
'Kills', 'Deaths'
],
datasets: [
{
backgroundColor: ['#f56954', '#00c0ef'],
data: [kills, deaths]
}
]
};
var pieChartTarget = $('#playerKD').get(0).getContext('2d');
var pieChart = new Chart(pieChartTarget, {
type: 'pie',
data: pieChartData
});
}));
}
}
playerOne.php should then look like this:
$team_id = 0;//initialize team ID
if(isset($_GET['team_id'])) {
$team_id = $_GET['team_id'];
}
//double quotes are important so the $team_id variable will be interpreted to the value it holds
$query = "SELECT * FROM user WHERE team_id = $team_id LIMIT 1";
$select_team = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($select_team);
$user_id = $row['user_id'];
$query = "SELECT SUM(game_stats.match_stats_kills) AS Kills, SUM(game_stats.match_stats_deaths) AS Deaths FROM game_stats WHERE game_stats.user_id = $user_id";
$select_kd = mysqli_query($connection, $query);
$data = array();
foreach($select_kd as $row) {
$data[] = $row;
}
mysqli_close($connection);
echo json_encode($data);

Related

My AJAX not outputting properly for chart

Does anyone have any idea why my AJAX function is returning each character individually. E.g.
testNew.html:150 i
testNew.html:150 t
testNew.html:150 e
testNew.html:150 m
It should be returning full words on a chart. But its printing individual letters on the console and is printing undefined on the chart.
AJAX code in javascript
$(document).ready(function(){
$.ajax({
url: "BaseClass.php",
data: { action : 'getResults' },
datatype: "application/json",
method: "GET",
success: function(data) {
console.log(data); // Produces the whole array of data from the php query fine.
var item = [];
var freq = [];
for(var i in data) {
console.log(data[i]); //produces each letter individually
item.push("Item " + data[i].item_description);
freq.push(data[i].item_id);
}
console.log(data[0].item_description); //Outputs undefined
var chartdata = {
labels: item,
datasets : [
{
label: '...',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: freq
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
MySQLDao.php - holds all the queries, gets result of the queries and sends to javascript:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults()
{
$sql = "SELECT * FROM item";
$result = $this->mysqli->query($sql);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
return $data;
}
}
?>
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
//$param=$_REQUEST['action'];
//echo json_encode($_GET);
//echo var_dump(json_encode($_GET));
$handle = fopen("php://input", "rb");
$param = $_REQUEST['action'];
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
ob_clean();
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
$result = $dao->getResults($recieved);
}
$dao->closeConnection();
//Return the result of the query
ob_clean();
//echo json_encode("param" .$param);
//echo json_encode("body" .$body);
//echo json_encode("recieved" .$recieved);
//echo json_encode("result" .$result);
echo "Your message : ", json_encode($result);
exit();
}
?>

php returns empty JSON array

I created an array for town name, "Auckland" and "Hamilton", but the response from php is always empty, any idea?
UPDATE:
after debugging, I found that the problem is in php query
" where town = '$town' ", once i deleted this line, the rest works perfectly.
But I still can't figure out why :<
javascript:
var _addNewTowntoList = function(){
if (_request.readyState == 4) {
if (_request.status == 200) {
var data = JSON.parse(_request.responseText);
if(data.length == 0){
alert("No such town");
return;
}
var t = data[0].town;
var o = data[0].outlook;
var min = data[0].min_temp;
var max = data[0].max_temp;
var witem = new WLine(t,o,min,max);
console.log(t+" "+o+" "+min+" "+max);
_list.push(witem);
}
}
}
here is the php
$town = $POST_['town'];
$query = "Select * From weather WHERE town = '$town'";
$result = mysqli_query($conn, $query);
//create array for data
$data = array();
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
echo json_encode($data);
change this
$town = $POST_['town'];
> $query = "Select * From weather WHERE town = '$town'";
to
$town = $_POST['town'];
$query = "Select * From weather WHERE town = '".$town."'";
Remember to properly escape the query string
$town = mysqli_real_escape_strin($conn, $_POST['town']);
Because else your script is opened to SQL Injection attack
The other thing to mention here other than correct name for the $_POST is that you can use mysqli_fetch_all function to fetch all results at once and avoid the loop. For example
echo json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));

I can not get data from jQuery muscles

I am learning tutorial, but I understand that the author made a mistake / mistakes.
The data is sent via GET in php and write, but do not turn back.
JavaScript:
function loadAllPost() {
var divs = $("#posts");
$.get("twitor.php?action=last", function() {
var posts = [];
for(var i = 0; i < posts.length; i++) {
var newPost = addNewPost(posts[i].name, posts[i].text, posts[i].date);
posts.push(newPost);
}
divs.children().remove();
divs.append(posts);
});
}
$(function() {
loadAllPost();
setInterval(loadAllPost, 5000);
$("#submit").click(function() {
var newPostName = $("#name").val();
var newPostText = $("#text").val();
var newPostDate = (new Date()).toLocaleString();
var newPost = addNewPost(newPostName, newPostText, newPostDate);
newPost.hide();
$("#posts").append(newPost);
newPost.slideToggle();
$("name").val("");
$("text").val("");
$.post("twitor.php?action=new", {
text: newPostText,
name: newPostName
});
});
});
Ie like php sends data, but does not have JS embeds them in HTML.
PHP:
if ($_GET['action'] == 'new') {
addNewPost();
}
elseif ($_GET['action'] == 'last') {
getLastPosts();
}
function getPDO(){
$db_host = "****";
$db_name = "****";
$db_user = "****";
$db_pass = "****";
$PDO = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
//$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
return $PDO;
}
function addNewPost(){
$params = [];
$params['name'] = $_POST['name'];
$params['text'] = htmlspecialchars($_POST['text']);
$PDO = getPDO();
$Statement = $PDO->prepare("INSERT INTO posts(`name`, `text`, `date`) VALUES (:name, :text, NOW());");
$Statement->execute($params);
}
function getLastPosts() {
$PDO = getPDO();
$Statement = $PDO->query("SELECT * FROM posts ORDER BY date DESC LIMIT 15");
if(!$Statement) return;
$posts = $Statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($posts);
}

ajax search bar multiple url value

In ajax url parameter i try to use multiple value to search. one value's data from user what they're enter. The other value will detect event.
but after i enter value there's no result.
here's my code(JS):
var currentURL = window.location.href;
currentURL = currentURL.split("=");
currentURL = currentURL[1];
console.log('php/Search.php?key=%QUERY' + currentURL);
$('#search.typeahead').typeahead({
name: 'typeahead',
remote: 'php/Search.php?key=%QUERY&map='+parseInt(currentURL[1]),
limit: 100
});
here's my code(PHP):
$key = $_GET['key'];
$map = $_POST['map'];
echo $map;
$array = array();
$array2 = array();
list($key2, $map) = split(',_+', $key);
$con = mysql_connect("localhost","test","test");
mysql_set_charset('utf8');
$db = mysql_select_db("test",$con);
$query = mysql_query("select `indicate_id`,`indicate_name` from `map_node` where `indicate_id` LIKE '%{$key}%' and map_sn =".$map." ;");
while ($row = mysql_fetch_assoc($query))
{
$array[] = $row['indicate_id'] ."\n\n". $row['indicate_name'];
}
echo json_encode($array);

php pass json to angularjs

this is my php code,
$count=mysql_num_rows($query);
if ($count > 0) {
// output data of each row
$foodList[] = array();
while($row =mysqli_fetch_assoc($result))
{
$foodList[] = $row;
}
} else {}
echo json_encode($foodList);
this is my js code:
var $promise = $http.post('foodList.php');
$promise.then(function(msg){
var foodList = msg.data;
if (foodList)
{
//$scope.foodList = foodList;
alert(foodList);
}
else
{
//$scope.msg = "Error user name or password";
}
this is output:
$promise.then(function(msg){*msg = Object {data: Array[1], status: 200, config: Object, statusText: "OK"}*
var foodList = msg.data;*foodList = [Array[0]]*
So: actually 3 data in my data base, but in output just only Array[1]?
How to fix it ?
THX
Your count the $query variable so in your while loop use $query variable
<?php
$count=mysql_num_rows($query);
if ($count > 0) {
// output data of each row
$foodList = array();
while($row =mysqli_fetch_assoc($query))
{
$foodList[] = $row;
}
}
echo json_encode($foodList);
?>
Your php syntax and the usage of commands are wrong in some places. Here is the corrected code. Please compare and see the difference.
$count=mysql_num_rows($result);
if ($count > 0) {
// output data of each row
$foodList = array();
while($row =mysqli_fetch_assoc($result))
{
array_push($foodList, $row);
}
}
echo json_encode($foodList);
This should work if you are selecting the rows correctly.

Categories

Resources