Grabbing SQL data using PHP then sending Array to Javascript - javascript

I am trying to figure out how to parse the SQL data I pulled using PHP to a javascript file.
I need to store the PHP array into java because I have a graph that uses a javascript array to populate the data.
Right now I have a button that refreshes my graph data, and when it is clicked it calls this javascript that's included in my main HTML file:
button.js
$(function(){
$('#refreshchart').click(function() {
var chart = $('#chart').highcharts();
chart.series[0].setData(dataarray);
});
});
The Java array "dataarray" needs to be pulled from a SQL database.
I have a PHP script that pulls the required data from the database.
Here is my PHP script:
query.php
<?php
include 'dbcon.php';
$query0 = "SELECT count(*) FROM test WHERE ans=0";
$query1 = "SELECT count(*) FROM test WHERE ans=1";
$query2 = "SELECT count(*) FROM test WHERE ans=2";
$query3 = "SELECT count(*) FROM test WHERE ans=3";
$query4 = "SELECT count(*) FROM test WHERE ans=4";
$query5 = "SELECT count(*) FROM test WHERE ans=5";
$query6 = "SELECT count(*) FROM test WHERE ans=6";
$query7 = "SELECT count(*) FROM test WHERE ans=7";
$query8 = "SELECT count(*) FROM test WHERE ans=8";
$query9 = "SELECT count(*) FROM test WHERE ans=9";
$result0 = $mysqli->query($query0) or die($mysqli->error.__LINE__);
$result1 = $mysqli->query($query1) or die($mysqli->error.__LINE__);
$result2 = $mysqli->query($query2) or die($mysqli->error.__LINE__);
$result3 = $mysqli->query($query3) or die($mysqli->error.__LINE__);
$result4 = $mysqli->query($query4) or die($mysqli->error.__LINE__);
$result5 = $mysqli->query($query5) or die($mysqli->error.__LINE__);
$result6 = $mysqli->query($query6) or die($mysqli->error.__LINE__);
$result7 = $mysqli->query($query7) or die($mysqli->error.__LINE__);
$result8 = $mysqli->query($query8) or die($mysqli->error.__LINE__);
$result9 = $mysqli->query($query9) or die($mysqli->error.__LINE__);
$row0 = $result0->fetch_row();
$row1 = $result1->fetch_row();
$row2 = $result2->fetch_row();
$row3 = $result3->fetch_row();
$row4 = $result4->fetch_row();
$row5 = $result5->fetch_row();
$row6 = $result6->fetch_row();
$row7 = $result7->fetch_row();
$row8 = $result8->fetch_row();
$row9 = $result9->fetch_row();
echo "Number of people that chose A: ", $row1[0];
echo "<br>Number of people that chose B: ", $row2[0];
echo "<br>Number of people that chose C: ", $row3[0];
echo "<br>Number of people that chose D: ", $row4[0];
echo "<br>Number of people that chose E: ", $row5[0];
echo "<br>Number of people that chose F: ", $row6[0];
echo "<br>Number of people that chose G: ", $row7[0];
echo "<br>Number of people that chose H: ", $row8[0];
echo "<br>Number of people that chose I: ", $row9[0];
echo "<br>Number of people that chose J: ", $row0[0];
$array = array($row1[0],$row2[0],$row3[0],$row4[0],$row5[0],$row6[0],$row7[0],$row8[0],$row9[0],$row0[0]);
echo json_encode($array);
?>
Now I know that I am going to have to encode the PHP array using json so that it is properly formatted and that I am probably going to have to use AJAX to call the PHP script to get the data.
This is where I am getting stuck, I am not sure how to grab the results and parse them into the java array so that the graph can be updated with the results in the SQL database.
Any help would be much appreciated!
Thanks,
Christopher

If you want to call your php-code via ajax try:
$(function(){
var chart = $('#chart').highcharts();
$('#refreshchart').click(function() {
$.ajax({
type: "GET",
url: "some.php",
success: function(data) {
chart.series[0].setData($.parseJSON(data));
}
});
});
});
Just set "some.php" to your php-filename.

<script>
var contants = <?php echo json_encode($array); ?>
</script>
And then transform it into an array. jQuery's $.parseJSON(string) might help.

If possible, avoid writing dynamic JavaScript in your code, use webservices for this, you can get this data through AJAX call using jQuery for example.
$.ajax({
url: "query.php",
data: { json: "on" },
}).done(function(data) {
console.log(data);
alert("found " + data.length + " elements" + "\n" + "first one: " + data[0].name + " = " + data[0].total);
});
I would prefer to write like this:
<?php
include 'dbcon.php';
$query =
"SELECT 'A' AS name,count(*) AS total FROM test WHERE ans=0 UNION " .
"SELECT 'B' AS name,count(*) AS total FROM test WHERE ans=1 UNION " .
"SELECT 'C' AS name,count(*) AS total FROM test WHERE ans=2 UNION " .
"SELECT 'D' AS name,count(*) AS total FROM test WHERE ans=3 UNION " .
"SELECT 'E' AS name,count(*) AS total FROM test WHERE ans=4 UNION " .
"SELECT 'F' AS name,count(*) AS total FROM test WHERE ans=5 UNION " .
"SELECT 'G' AS name,count(*) AS total FROM test WHERE ans=6 UNION " .
"SELECT 'H' AS name,count(*) AS total FROM test WHERE ans=7 UNION " .
"SELECT 'I' AS name,count(*) AS total FROM test WHERE ans=8 UNION " .
"SELECT 'J' AS name,count(*) AS total FROM test WHERE ans=9";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$rows = $result->fetch_all(MYSQLI_ASSOC);
$print_json = !empty($_GET['json']) && $_GET['json']=='on'; // your content negotiation logic here
if ($print_json) {
header('Content-Type: application/json');
echo json_encode($rows);
} else {
foreach ($rows as $row) {
echo "Number of people that chose {$row['name']}: {$row['total']}";
}
}
This way you have more control and a cleaner code. I think you code improve SQL, though.

this code is working
var str_array=[];
function something()
{
str_array= <?php echo json_encode($array); ?>;
alert(str_array);`
}

Related

How to display data in an object

When outputting data, they are displayed in one line. How to make sure that every record is an object and all objects turn into an array?
<?php
require_once("db.php");
$query = $db->query('SELECT * FROM `dictdb`.`dictwords`');
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo "
id: " . $row['id'] . ",
engWord: " . $row['engwords'] . ",
rusWord: " . $row['ruswords'] ."
";
}
?>
test.js
$(document).ready(function () {
$(".btn-test").on("click", function () {
$.ajax({
url: "/src/php/tests.php",
type: "POST",
success: function (data) {
$(".test-word").html(data);
}
})
})
Because you're inserting plain text into HTML. That's meant to be with <tags> ignoring your whitespace (like line breaks).
Either load some reasonable HTML from PHP
## in PHP
...
echo "<p>
id: " . $row['id'] . ",<br>
engWord: " . $row['engwords'] . ",<br>
rusWord: " . $row['ruswords'] ."<br>
</p>";
...
Or, better, work with JSON
## in PHP
...
$results = [];
while ($row = $query->fetch(PDO::FETCH_ASSOC))
$results[] = $row;
header('Content-Type: application/json');
echo json_encode($results);
...
## in JS
$.ajax('/src/php/tests.php')
.done(data => { // use .success for older jQuery versions
let formatedJSON = JSON.stringify(data, null, 2);
$(".test-word").html(`<pre>${formatedJSON}</pre>`);
});
Put the desired HTML tags in the data you echo.
echo "<br>
id: " . $row['id'] . ",<br>
engWord: " . $row['engwords'] . ",<br>
rusWord: " . $row['ruswords'] ."<br>
";
Your echo does not produce a JSON object. You would need to do something like:
<?php
require_once("db.php");
$query = $db->query('SELECT * FROM `dictdb`.`dictwords`');
$response = [];
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$response[] = [
'id' => $row['id'],
'engWord' => $row['engwords'],
'rusWord' => $row['ruswords'],
];
}
echo json_encode($response);
This would produce a JSON object similar to (if you had 2 results returned from DB):
[
{
id: 'YourID',
engWord: 'Your Eng Word',
rusWord: 'Your Rus Word',
}, {
id: 'YourID',
engWord: 'Your Eng Word',
rusWord: 'Your Rus Word',
},
]
Rather than try to parse HTML, i'd highly recommend using a JSON response.
When you use the function query you are asking for a query execution on your database. So, to see what returns in case of reading queries, you should check the doc of that function, but i'm pretty sure it's an object because when you do $query->fetch, you are using a method of that object.
Instead, for what concerns the array, just try to use a try-catch (my bad for repeating) handling exception block and see, if it gives you an error when converting to array, then it means you can't convert those data into an array.

Get data from database using php,ajax

I have a simple section in which I am displaying data from the database, my database looks like this.
Now I have four buttons looks like this
When a user clicks one of the above buttons it displays this
So now when user eg select construction and next select eg Egypt' in the console and clicks buttonconfirmdisplays [855,599075], user can select multiple countries, this works as expected forconstruction ,power,oil`,
Now I want if user eg clicks All available industries button in those four buttons and next select eg Egypt and click confirm it should display
the sum of egypt total projects in construction, oil, power sector 855+337+406 =1598 and the sum of total budgets in both sectors 1136173
Here is my solution
HTML
<div id="interactive-layers">
<div buttonid="43" class="video-btns">
<span class="label">Construction</span></div>
<div buttonid="44" class="video-btns">
<span class="label">Power</span></div>
<div buttonid="45" class="video-btns">
<span class="label">Oil</span></div>
<div buttonid="103" class="video-btns">
<span class="label">All available industries</span>
</div>
</div>
Here is js ajax
$("#interactive-layers").on("click", ".video-btns", function(){
if( $(e.target).find("span.label").html()=="Confirm" ) {
var selectedCountries = [];
$('.video-btns .selected').each(function () {
selectedCountries.push( $(this).parent().find("span.label").html() ) ;
});
if( selectedCountries.length>0 ) {
if(selectedCountries.indexOf("All available countries")>-1) {
selectedCountries = [];
}
} else {
return;
}
var ajaxurl = "";
if(selectedCountries.length>0) {
ajaxurl = "data.php";
} else {
ajaxurl = "dataall.php";
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
countries: selectedCountries.join(","),
sector: selectedSector
},
success: function(result){
console.log(result);
result = JSON.parse(result);
$(".video-btns").each(function () {
var getBtn = $(this).attr('buttonid');
if (getBtn == 106) {
var totalProjects = $("<span class='totalprojects'>"+ result[0] + "</span>");
$(this).append(totalProjects)
}else if(getBtn ==107){
var resultBudget = result[1]
var totalBudgets = $("<span class='totalbudget'>"+ '&#36m' +" " + resultBudget +"</span>");
$(this).append( totalBudgets)
}
});
return;
}
});
}
});
Here is php to get all dataall.php
$selectedSectorByUser = $_POST['sector'];
$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser ) {
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}
}
echo json_encode([ $totalProjects, $totalBudget ] );
exit();
?>
Here is data.php
<?php
$selectedSectorByUser = $_POST['sector'];
$countries = explode(",", $_POST['countries']);
//var_dump($countries);
$conn = mysqli_connect("localhost", "root", "", "meedadb");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser && in_array($row['Countries'],$countries ) ) {
// array_push($data, $row);
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}
}
// array_push($wynik, $row);
echo json_encode([ $totalProjects, $totalBudget ] );
//echo json_encode($data);
exit();
?>
Now when the user clicks All available industries btn and selects a country I get [0,0] on the console.
What do I need to change to get what I want? any help or suggestion will be appreciated,
in you dataAll.php
If you have select All available industries
you shold not check for sector because you need all sector (eventually you should check for countries )
so you should avoid the check for this condition
<?php
$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = [];
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result)) {
$totalProjects += $row['SumofNoOfProjects'];
$totalBudget += $row['SumofTotalBudgetValue'];
}
echo json_encode([$totalProjects, $totalBudget]);
You can use the SQL JOIN operator, or in this case an implicit join would be cleanest:
$result = mysqli_query($conn, "SELECT * FROM construction, power, oil_and_gas, industrial WHERE construction.Countries = power.Countries AND power.Countries = oil_and_gas.Countries AND oil_and_gas.Countries = industrial.Countries");
You need the WHERE conditions so it knows how the rows of each different table are related to each other. You can shorten it a bit with aliases for the tables:
$result = mysqli_query($conn, "SELECT * FROM construction as C, power as P, oil_and_gas as G, industrial as I WHERE C.Countries = P.Countries AND P.Countries = G.Countries AND G.Countries = I.Countries");
In this case, however, I think you may want to consider changing the structure of your database. It seems like you repeat columns quite a bit across them. Perhaps these can all be in a single table, with a "type" column that specifies whether it's power, construction, etc. Then you can query just the one table and group by country name to get all your results without the messy joins across 4 tables.
The single table looks OK.
(The rest of this Answer is not complete, but might be useful.)
First, let's design the URL that will request the data.
.../foo.php?industry=...&country=...
But, rather than special casing the "all" in the client, do it in the server. That is, the last button for industry will generate
?industry=all
and the PHP code will not include this in the WHERE clause:
AND industry IN (...)
Similarly for &country=all versus &country=egypt,iran,iraq
Now, let me focus briefly on the PHP:
$wheres = array();
$industry = #$_GET['industry'];
if (! isset($industry)) { ...issue error message or use some default... }
elseif ($industry != 'all') {
$inds = array();
foreach (explode(',', $industry) as $ind) {
// .. should test validity here; left to user ...
$inds[] = "'$ind'";
}
$wheres[] = "industry IN (" . implode(',', $inds) . )";
}
// ... repeat for country ...
$where_clause = '';
if (! empty($wheres)) {
$where_clause = "WHERE " . implode(' AND ', $wheres);
}
// (Note that this is a generic way to build arbitrary WHEREs from the data)
// Build the SQL:
$sql = "SELECT ... FROM ...
$where_clause
ORDER BY ...";
// then execute it via mysqli or pdo (NOT mysql_query)
Now, let's talk about using AJAX. Or not. There were 2 choices:
you could have had the call to PHP be via a GET and have that PHP display a new page. This means that PHP will be constructing the table of results.
you could have used AJAX to request the data. This means that Javascript will be constructing the data of results.
Which choice to pick probably depends on which language you are more comfortable in.

visually show counter from id in MySQL

I have a database with 100 rows. I have a button that shuffle those id's and print out 3 random ids.
HTML
<form method="post">
<button>Shuffle</button>
</form>
PHP
$sql = "SELECT id, description FROM fantasies_original ORDER BY RAND ( ) LIMIT 3";
$res = $mysqli->query($sql);
//print($res);
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
echo "Store Number: " . $row["id"]. "<br>" .
"Description: " . $row["description"]. "<br><br>";
}
} else {
echo "0 results";
}
I would like to visualize the counter. So when I press the button I can see the number of the id there is loop through in the database. I have been looking everywhere to find a library that could do the job.
Does anybody knows a library or have a suggestion how to do that?

How to get json Format from a sql-multi-query php-script to javascript?

I have a question for a project.
I have a PHP-Script on a server like this:
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$sql = "SELECT COUNT(*) as f FROM R;";
$sql.= "SELECT COUNT(*) as fo FROM Ro;";
$sql.= "SELECT P, U, D FROM Profile where U = 'lol';";
$sql.= "SELECT IU FROM I WHERE UID = '2';";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
echo json_encode($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
I get a response like this:
[{"f":"0"}][{"fo":"0"}][{"P":"0",U":"lol","D":"xD"}]
[{"I":"lol"},{"I":"lolol"}]
But when I request this reponse via javascript like:
$.post("http://localhost/lol/lol.php", {}, function(data){
console.log(data);
}, "json");
I receive null.
But when I use the post.request without "json", I get a response but not in json format.
How can I do this?
Thank You very much for your help!!!
Regards
Felix
The answer was the following:
$.post("http://localhost/lol.php", {}, function(data){
var pars1 = data.split('][').join(']-[');
var pars2 = pars1.split('\\n ').join('');
var pars3 = pars2.split('-');
var f = JSON.parse(pars3[0]);
var fo = JSON.parse(pars3[1]);
var po = JSON.parse(pars3[2]);
var i = JSON.parse(pars3[3]);
Now you have 4 JSON Format Objects.

How to get PHP shuffle results to show up one at a time throughout shuffle

Say I have 10 items in my db that I am trying to shuffle, how could I alter my current code so that every time it pulls a name out of the db that it shows up one at a time, rather than all at once?
$con = mysqli_connect("XXX", "XXX", "XXX", "XXX");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
echo 'Normal results: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
?>
<form method="post">
<input type="submit" value="Shuffle" name="shuffle">
</form>
<?php
if (isset($_POST['shuffle'])) {
shuffle($array);
echo 'Shuffled results: <br>';
foreach ($array as $result) {
$shuffle_firstname = $result['firstname'];
$shuffle_lastname = $result['lastname'];
?>
<div id="shuffle_results">
<?php echo $shuffle_firstname . ' ' . $shuffle_lastname . '<br>';?>
</div>
<?php }
}
//What I added in and this is the spot I added it as well
$get_shuffle = array($array);
$shuffle_one = array_pop($get_shuffle);
print_r($get_shuffle);
?>
I want them all to stay put once they have shown.. I just want all of them to come out one at a time. Say, there is 10 pieces of paper in a bag and you are drawing one at a time and then put the pieces of paper on a table to show what was drawn, that is what I want.
As a follow up to my comment suggesting you use JavaScript instead of PHP for the animation, here is a basic way to do it. (This code assumes you have jQuery on the page).
Note: I haven't tested this code and there is likely a bug or two, but I hope you get the general idea.
Your HTML
<div id="shuffle_results"></div>
<form onsubmit="getData()">
<input type="submit" value="Shuffle" name="shuffle">
</form>
Your PHP
$con = mysqli_connect("localhost", "root", "", "db");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
array_push($array, $row);
}
header('Content-Type: application/json');
echo json_encode($array);
Your JavaScript
function getData() {
$.ajax({
url: 'url to PHP script',
dataType: 'json',
success: function(data) {
for(var i = 0, l = data.length; i < l; ++i) {
window.setTimeout(addResult, 2000, data[i].firstname, data[i].lastname);
}
},
error: function(jqXHR, textStatus, error) {
alert('Connection to script failed.\n\n' + textStatus + '\n\n' + error);
}
});
}
function addResult(firstname, lastname) {
$('#shuffle_results').append("<p>" + firstname + " " + lastname + "</p>");
}
The basic idea here is that you shouldn't use PHP to do DOM manipulation. PHP can load data into your webpage (and that data can be DOM elements, JSON data as I have shown, or other types of data), but once there JavaScript should be used to interact with it. Recall, PHP runs on your server, while JavaScript (traditionally) runs in the client's web browser.

Categories

Resources