SELECT Count from mysql to Google Geo Chart - javascript

I've been trying to retrieve data from mysql database using SELECT Count, as I got a list of countries which I want to count how many times each country is displayed in the column SovereignState, to a Google Geo Chart and by browsing around, I believe that json_encode should do the trick.
However, I have no idea how to get make a json_encode from my php code and then put it in the DataTable of the chart.
This is the php code:
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD','');
define('DB_HOST', '');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) ;
if ($conn->connect_error) {
die ('Could not connect: ' . $conn->connect_error);
}
$sql = "SELECT SovereignState, COUNT(*) FROM Data_2 GROUP BY SovereignState";
echo $sql;
//$result = $conn->query($sql);
$result = $conn->multi_query($sql);
if(!$result) {
echo "Could not successdully run query ($sql) from DB: " . mysql_error(); exit;
}
echo "<pre>";
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s - %s\n", $row[0], $row[1]);
}
$result->free();
}
} while ($conn->more_results());
echo "</pre>";
$conn->close();
And this is the html code of the google geochart:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Number'],
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>

You can use json_encode() from your PHP code and use Ajax in order to get the JSON into your JS code.
Also, (not recommended) you can just call a PHP function from your JS code with <?php myFunction();?>, that function should return an echo json_encode().

Related

Update Database with javascript variable/ transfare javascript variable to php

I want to Update my database with a variable from javascript.
This is my javascript code i want the testusersGeld variable to transfare over to php.
var testusersGeld = 111;
var sendUsersGeld = new XMLHttpRequest();
sendUsersGeld.open("POST", "usersGeldSenden.inc.php");
sendUsersGeld.setRequestHeader("Content-Type", "application/json");
sendUsersGeld.send(testusersGeld);
and this is my php code:
<?php
session_start();
$requestPayload = file_get_contents("php://input");
$object = json_decode($requestPayload);
var_dump($object);
if(isset($_POST['update']))
{
require_once 'includes\dbh.inc.php';
$query = "UPDATE users SET usersGeld='".$object."' WHERE usersName LIKE '{$_SESSION["usersName"]}'";
$result = mysqli_query($conn, $query );
if($result)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
mysqli_close($conn);
}
When i var_dump than i can see the 111 but when i try to echo it out it wont work. The part of Update works when i use another variable.

Jquery .get call not returning anything

I've been at this for hours trying to figure out why this will not work. I am trying to read data from my mysql database using php and jquery. In my php file it loops through a table and should echo the results of that table. I am using the jquery .get method to try and retrieve it but i get a 404 error file not found. The 404 error goes away and everything works fine if i change my php file to something simple like:
<?php echo 'Hello'; ?>
I believe the problem is in my php file because when i create a new file with just echoing a string and nothing else it returns everything fine.
$(document).ready(function() {
$.get("php/listtasks.php", function(data){
alert("Data: " + data);
})
});
My php file where i think there is a problem contains:
<?php // sqltest.php
require_once 'session.php';
require_once 'login.php';
$conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($conn->connect_error) die($conn->connect_error);
$query = "SELECT * FROM list";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo $row[2];
}
$result->close();
$conn->close();
?>

Unable to load JSON into D3.js from MySQL using PHP

I am retrieving contents from my database(MYSQL) in PHP. The following is my PHP script:
<?php
$username = "**";
$password = "**";
$host = "**";
$database="**";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "
SELECT * FROM data1
";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
The output is a perfectly formatted JSON Object:
[{"ID":"1","Country":"India","Value1":"100","Value2":"200"},{"ID":"2","Country":"India","Value1":"230","Value2":"800"},{"ID":"3","Country":"USA","Value1":"30","Value2":"300"},{"ID":"4","Country":"Sri Lanka","Value1":"320","Value2":"330"},{"ID":"5","Country":"Sri Lanka","Value1":"120","Value2":"90"},{"ID":"6","Country":"Sri Lanka","Value1":"420","Value2":"890"},{"ID":"7","Country":"China","Value1":"20","Value2":"890"},{"ID":"8","Country":"China","Value1":"430","Value2":"999"},{"ID":"9","Country":"Canada","Value1":"200","Value2":"319"},{"ID":"10","Country":"Canada","Value1":"1000","Value2":"29"}]
I want to use this JSON object as input to my D3.js graph.
When I try to create my D3 chart I get the error in my browsers log:
SyntaxError: Unexpected token < in JSON at position 0(…)
The following is my D3 code where i invoke the PHP file and try to parse the JSON:
d3.json("1.php", function(error, data) {
console.log(error);
//parsing operations
});
Any pointers would be appreciated. Thanks

jQuery Autocomplete PHP Mysql posting different field

I am making use of jQuery's Autocomplete where I am populating my autocomplete dropdown with a php file called site.php. Site.php gets the values from a mysql table called site and which has 3 columns: id, code and site. I want my autocomplete to show only code and site and then store the corresponding id in my other table.
Everything works fine except that autocomplete is posting the code and the site selected but not the id. What do I need to change in order to send the id to my php POST and not code and site? Scripts as follows:
PHP file: site.php
<?php
$server = 'sql203.com';
$user = 'xxxxxxxxxxxx';
$password = 'xxxxxxx';
$database = 'b17';
$mysqli = new MySQLi($server,$user,$password,$database);
/* Connect to database and set charset to UTF-8 */
if($mysqli->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
exit;
} else {
$mysqli->set_charset('utf8');
}
/* retrieve the search term that autocomplete sends */
$term = trim(strip_tags($_GET['term']));
$a_json = array();
$a_json_row = array();
if ($data = $mysqli->query("SELECT * FROM `b17_16413362_upupa`.`site` WHERE code LIKE '%$term%' OR site LIKE '%$term%' ORDER BY code , site")) {
while($row = mysqli_fetch_array($data)) {
$id = htmlentities(stripslashes($row['id']));
$code = htmlentities(stripslashes($row['code']));
$site = htmlentities(stripslashes($row['site']));
$a_json_row["id"] = $id;
$a_json_row["value"] = $code.' '.$site;
$a_json_row["label"] = $code.' '.$site;
array_push($a_json, $a_json_row);
}
}
// jQuery wants JSON data
echo json_encode($a_json);
flush();
$mysqli->close();
?>
Javascript:
<script type="text/javascript">
$(function() {
$("#sitex").autocomplete({
source: 'site.php',
minLength: 0
}).focus(function(){
$(this).autocomplete("search");
});
});
</script>
In your PHP, change
$a_json_row["value"] = $code.' '.$site;
to
$a_json_row["value"] = $id;
The 'value' property is the data that will be submitted by the form. The 'label' property is what will be displayed to the user.

how to fetch data from sql using form $_Post id in where clause

I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch

Categories

Resources