PHP MySQL Data To AngularJS - mysql

I am using this code to pull data from a MySQL.
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var icon = data[1];
var english = data[2];
var british = data[3];
$('#output').html("<b>id: </b>"+id+"<b> icon: </b>"+icon+"<b> english: </b>"+english+"<b> british: </b>"+british); //Set output element html
}
And it outputs this correctly but my questions is how would put this data into the below.
$scope.items = [
{
english: '<First Row english>',
british: '<First Row british>',
image: '<First Row icon>'
},
{
english: '<Second Row english>',
british: '<Second Row british>',
image: '<Second Row icon>'
}
//So on and so forth for all the records in the DB.
]
This is from api.php not sure if this needs to be returned a certain way?
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
echo $json_response = json_encode($arr);
?>

<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
$arr[];
while($obj = mysql_fetch_object($query)) {
array_push($arr, $obj);
}
echo $json_response = json_encode($arr);
?>
JS
$http.get('api.php').success(function(data) {
$scope.items = data;
});

Related

How to add latest TimesStamp to Google Gauge

I need help adding latest TimesStamp to page that displays Google gauge. I have made gauge work and auto refresh without the need to refresh the page, but now I need to display on it, or next to it when the latest entry in database was made (displaying TimesStamp of value that is currently displayed in gauge). Here's my code so far:
Chart.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 800, height: 240,
greenFrom: 98, greenTo: 100,
yellowFrom:90, yellowTo: 98,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData);
chart.draw(data, options);
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="chart_div" style="width: 800px; height: 240px;"></div>
</body>
</html>
And here's getdata.php
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
}
mysqli_close($conn);
// write data array to page
echo json_encode($data);
?>
we need to include the timestamp in the data we return from php.
first, add the field to the select statement, here...
$sql = "SELECT ProductPurity, TimesStamp FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
next, we use a variable to save the timestamp...
// create data array
$data = [];
$data[] = ["Label", "Value"];
$stamp = null;
then, in the while loop, we save the value of the timestamp...
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
$stamp = $row["TimesStamp"]
}
finally, we combine both the chart data and timestamp in an object to send to the page.
$data = array('rows' => $data, 'timestamp' => $stamp);
following is the updated php snippet...
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity, TimesStamp FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
$stamp = null;
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
$stamp = $row["TimesStamp"]
}
mysqli_close($conn);
// write data array to page
$data = array('rows' => $data, 'timestamp' => $stamp);
echo json_encode($data);
?>
then on the html page, we need to adjust how we receive the data...
to receive the chart data, we need to use the 'rows' property from the data.
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData.rows); // <-- add .rows
and we can receive the timestamp as follows...
jsonData.timestamp
not sure how you want to display the timestamp, here a <div> is used.
so to update the new <div> element...
document.getElementById('timestamp').innerHTML = jsonData.timestamp;
following the updated html snippet...
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData.rows);
chart.draw(data, options);
// update timestamp
document.getElementById('timestamp').innerHTML = jsonData.timestamp;
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="timestamp"></div>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>

comparing json submitted array and sql returned array and printing difference in text file

I am submitting a javascript array to another php page via ajax which runs a query and returns another array. Then i would like to compare these two arrays and print the difference in a text file. The code give below is creating a text file with no data in it.
Here is the code
$('#tabletomodify').on('change','.street',
function (event)
{
event.preventDefault();
var row=( $(this).closest('tr').prop('rowIndex') );
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var ideSelected= this.id;
var values = '[';
values+=valueSelected+",";
for ($i=3;$i<row;$i++)
{
var dv="selectcity"+$i;
var dv1=document.getElementById(dv).value;
var sl="street"+$i;
var sl1=document.getElementById(sl).value;
var po="building"+$i;
var po1=document.getElementById(po).value;
var concat=dv1+sl1+po1;
values+=''+concat+',';
}
values = values.substring(0,values.length-1);
values += ']';
$.ajax({
url: "get_buildings.php",
type: 'POST',
data: {data: values} ,
success: function(){
alert("Success!")
}
});
the value sent to the get_buildings.php is
[newyork::roosevelt st,springfieldevergreen terraceno42,quahogspooner streetno43]
Php code get_buildings.php:-
$a1='newyork::roosevelt st';
$sl= explode("::",$a1);
$a=$sl[1];
$connection_buildings= mysqli_connect('localhost', 'xxxx', 'xxxx', 'DETAILS') or die ('Cannot connect to db');
$sql_query_3 = "select buildings from $a";
$result_query_3=mysqli_query($connection_buildings,$sql_query_3) or die ("check it");
$options=array();
while ($row = $result_query_3->fetch_assoc())
{
$name = $row['buildings'];
$val=$a.$sl[0].$name;
array_push($options,$val);
}
$result = array_diff($_POST['data'], $options);
$fp = fopen("textfile.txt", "w");
fwrite($fp, $result);
fclose($fp);
mysqli_close($connection_buildings);

Ajax GET content from php page

Hi I have a table which I am trying to update with a call to a MySQL database in a separate php page. This separate page loops through a result set and builds the table through a series of echos. In the main page I am trying to insert that echoed content into a div.
This is all kicked off by the user selecting an option from a drop down box.
This is the separate php page. (It works fine when i manually type in the GET parameters, it is the link between the two pages which doesn't seem to work)
tableGetter.php
<?PHP
$user_name = "rocketeermus_pr";
$password = "zuluhead2";
$database = "rocketeermus_pr";
$server = "pdb1.awardspace.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
echo "Bonjour";
if (isset($_GET['composer'])){
echo "Helloooo";
if ($db_found) {
echo "SELECT * FROM catalogue WHERE Composer = '".mysql_escape_string($_GET['composer'])."';";
$SQL = "SELECT * FROM catalogue WHERE Composer = '".mysql_escape_string($_GET['composer'])."';";
$result = mysql_query($SQL);
setlocale(LC_MONETARY,"en_GB");
echo "<table class=\"sortable\" id=\"moder\" width=\"800\">";
echo "<th>TITLE</th><th>COMPOSER</th><th>VOICING</th><th>PRICE</th><th></th></tr>";
while ( $db_field = mysql_fetch_assoc($result) ) {
echo "Hi.";
echo "<tr><td>{$db_field['Title']}</td><td>{$db_field['Composer']}</td><td>{$db_field['Voicing']}</td><td>";
echo money_format("%n", $db_field['Price']);
echo "</td><td> <div class=\"product\"> <input value=\"{$db_field['Title']}\" class=\"product-title\" type=\"hidden\"> <input value=\"0.5\" class=\"product-weight\" type=\"hidden\"> <input value=\"{$db_field['NoVox']}\" class=\"googlecart-quantity\" type=\"hidden\"> <input value=\"{$db_field['Price']}\" class=\"product-price\" type=\"hidden\"> <div title=\"Add to cart\" role=\"button\" tabindex=\"0\" class=\"googlecart-add-button\"> </div> </div> </td></tr>";
}
echo "</table>";
mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
}
?>
And here is the important stuff from the main page:
Javascript:
function getdata()
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
var queryString1 = "";
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
var ajaxSearchResults1 = document.getElementById("table");
ajaxSearchResults1.innerHTML = req.responseText;
// only if http status is "OK"
if (req.status == 200)
{
var new1 = document.getElementById('composer').value;
queryString1 = "?composer=" + encodeURIComponent(new1);
console.log (queryString1);
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", "tableGetter.php" + queryString1, true);
req.send();
}
}
function getXMLHTTP() {
var xmlhttp;
if(window.XMLHttpRequest){ //For Firefox, Mozilla, Opera, and Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){ //For ie
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
html:
<div id="menus">
<table>
<tr>
<td><form action=""">
<select name="composer" id ="composer" onchange="getdata();">
<?php
$user_name = "***";
$password = "****";
$database = "****";
$server = "****.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT DISTINCT Composer FROM catalogue ORDER BY Composer";
$result = mysql_query($SQL);
setlocale(LC_MONETARY,"en_GB");
while ( $db_field = mysql_fetch_assoc($result) ) {
?>
<option id="composer" onchange="getdata();" value="<?php echo $db_field['Composer'];?>">
<?php
echo $db_field['Composer'];
?>
</option>
<?php
}
}
?>
</select>
</form></td>
</tr>
</table>
</div>
<div id="table">
<?php include("tableGetter.php"); ?>
</div>
The html on the main page works fine, the drop down menu fills up nicely with all the distinct composer names in the database. When an option in the menu is selected the only thing echoed in the "table" div is "Bonjour". It's not getting further than if (isset($_GET['composer'])) in the tableGetter.php page. I'm printing out the queryString1 variable (The get parameters) which is requested in the getData() function and it reports: ?composer=Animuccia%2C%20Paulo which works perfectly when loading the page manually. It just won't work dynamically!
Anybody know what's going on here?
You aren't setting queryString1 before sending the AJAX request. Try this rewrite of getdata().
function getdata()
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
var ajaxSearchResults1 = document.getElementById("table");
ajaxSearchResults1.innerHTML = req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
var new1 = document.getElementById('composer').value;
var queryString1 = "?composer=" + encodeURIComponent(new1);
req.open("GET", "tableGetter.php" + queryString1, true);
req.send();
}
}

Populating amchart dynamically fetching data from mysql

I am trying to fetch records from mysql and render the data via amchart, but I am facing difficulty in doing so. I have written the following code which is not working. The query works fine but the problem is replacing the static (placeholder) data with the results of the query. Please suggest.
{
$selectdata="SELECT member_lhp, COUNT( * ) AS 'land_pattern' FROM hh_basic_info GROUP BY member_lhp";
$resdata=mysql_query($selectdata);
<script type="text/javascript">
var chart;
var chartData = [
<?php
$count=0;
while($rowdata = mysql_fetch_assoc($resdata))
foreach($rowdata as $rows){
$type= $rows['member_lhp'];
$lp=$rows['land_pattern'];
if($count++ > 0) echo ',';
?>
{
year: <?php echo $type;?>,
income: <?php echo $lp;?>
},
<?php } ?>
];
AmCharts.ready(function () {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "year";
// this single line makes the chart a bar chart,
// try to set it to false - your bars will turn to columns
chart.rotate = true;
// the following two lines makes chart 3D
chart.depth3D = 20;
chart.angle = 30;
// AXES
// Category
var categoryAxis = chart.categoryAxis;
categoryAxis.gridPosition = "start";
categoryAxis.axisColor = "#DADADA";
categoryAxis.fillAlpha = 1;
categoryAxis.gridAlpha = 0;
categoryAxis.fillColor = "#FAFAFA";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.axisColor = "#DADADA";
valueAxis.title = "Villagers - Land holding pattern";
valueAxis.gridAlpha = 0.1;
chart.addValueAxis(valueAxis);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.title = "Income";
graph.valueField = "income";
graph.type = "column";
graph.balloonText = "Land holding number in [[category]]:[[value]]";
graph.lineAlpha = 0;
graph.fillColors = "#bf1c25";
graph.fillAlphas = 1;
chart.addGraph(graph);
// WRITE
chart.write("chartdiv");
});
</script>
}
At a quick glance it looks like you may have included an extra comma after your curly bracket. You are already adding a comma via the PHP if your count is greater than 0 so this would have been introducing a second, unnecessary one between each group of data.
You had the following...
{
year: <?php echo $type;?>,
income: <?php echo $lp;?>
},
try just having this instead...
{
year: <?php echo $type;?>,
income: <?php echo $lp;?>
}
It seems you forgot to parse in json format,
Just write
var newchartData= JSON.parse(chartData);
now assign newcharData to DataProvider,it should work.

phonegap/msql(i) can't establish connection to database

i'm currently developing an web app for iOS but the app can't get the connection right.
when i'm trying to log in, i get the following iOS popup: index.html Error.
while the PHP files are online,
here some of my code:
connection.php
<?php //Make connection with database
// Verbinden met MySQL Database
$host = "localhost"; // Welke server : localhost
$username = "*******"; // Gebruikersnaam
$password = "****"; // Wachtwoord
$dbnaam = "*****"; // Naam van de database
$db_error1 = "<p>FOUT: verbinden met databaseserver is mislukt</p>"; // Foutmelding 1
$db_error2 = "<p>FOUT: selecteren van database is mislukt</p>"; // Foutmelding 2
$db_error3 = "<p>FOUT: sluiten van database is mislukt</p>"; // Foutmelding 3
// Verbinden met Databaseserver
$con=mysqli_connect($host, $username, $password, $dbnaam);// or die($db_error1);
// verbinden met de database
//mysql_select_db($dbnaam, $db) or die($db_error2);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
demo.js
// define the URL of the server component
//var url ="http://www.jorisgraaumans.nl/dutchmobile/";
//var url = "http://localhost:8888/Mobile/Festival/";
var url = "http://www.rikvandoorn.com/mobile/";
// afvangen van het standaard submit event
// zie ook: http://api.jquery.com/submit/
$('#login').on('pageinit', function(event) {
$('#loginForm').submit(function() {
$.ajax({
type: "POST",
url: "processLogin.php",
cache: "false",
dataType: "json",
data: {
email : $('#email').val(),
wachtwoord : $('#wachtwoord').val(),
},
success: function(phpData){
$("#return").data("login", phpData.login);
console.log("login is: "+ phpData.login);
if(phpData['error'] == true){
$.mobile.changePage("#return", {
transition : "fade"
})
} else {
$.mobile.changePage("#home", {
transition : "fade"
})
}
},
error: function(){
alert('Error');
}
});
return false; // return false to prevent the default submit of the form to the server.
});
// end: pageinit loginForm
});
$('#return').on('pageshow', function(event) {
$("#error_message_log").empty();
$("#error_message_log").prepend('<p>' + $(this).data('login') + '</p>');
});
processLogin.php
<?php //process login form
include 'http://www.rikvandoorn.nl/mobile/connect.php'; //connection to database
if(empty($_POST['email']) || empty($_POST['wachtwoord'])){
$return['error'] = true; //return error
$return['login'] = 'Niet alle velden zijn ingevuld';
} else {
$email = $_POST['email'];
$wachtwoord = $_POST['wachtwoord'];
//Check if user exists
$sql = "SELECT * FROM gebruiker WHERE email = '$email'";
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows == 0){
$return['error'] = true;
$return['login'] = 'Gebruiker bestaat niet';
} else {
//Check if password is correct for user
$sql_2 = "SELECT * FROM gebruiker WHERE email = '$email' && wachtwoord = '$wachtwoord'";
$query_2 = mysql_query($sql_2);
$num_rows_2 = mysql_num_rows($query_2);
if($num_rows_2 == 0){
$return['error'] = true;
$return['login'] = 'Wachtwoord onjuist';
} else {
$return['error'] = false;
$return['login']['email'] = $email;
$return['login']['wachtwoord'] = $wachtwoord;
}
}
}
echo json_encode($return);
Unless you've riddled the code with typos, you're mixing two entirely seperate mysql libraries:
$con=mysqli_connect($host, $username, $password, $dbnaam);// or die($db_error1);
^---note the presence of an 'i'
and in the other scripts:
$result = mysql_query($sql) or die(mysql_error());
^---note the LACK of an 'i'
mysql and mysqli are NOT interchangeable, and connections established in one are utterly useless for the other.
The mysql (WITHOUT an i) library is obsolete and deprecated. Stick with mysqli (WITH an i) only.