Get data from database using php,ajax - javascript

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.

Related

How to get an value from a php page with js

I am trying to capture a value that is calculated on a PHP page called "classes_day.php" at the same time as I pass a value per GET, "? Day = YYYY-mm-dd" to it. How do I do this with JS or JQuery?
<?php
// aulas_dia.php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT * FROM `task` WHERE `dia` LIKE ".$data."";
$result = mysqli_query($link,$query);
$soma = 0;
while ($row = mysqli_fetch_assoc($result)) {
$soma = $soma+$row['duration'];
}
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
?>
I already tried using an iframe and contentwindow, but iframe gets the value and the contentwindow is empty (weird isn't it?).
Following Barmar's tip, I'm using $ .get, but I don't know why this loop is not working, can anyone help me?
for (i = 0; i < num_days; i++) {
x = (first_day+i)%7;
y = (first_day+i-x)/7;
h_dia(String(y)+String(x),i+1);
data_c = ano+"-"+mes+"-"+String(i+1);
$.get("aulas_dia.php?data="+data_c, function(data){
console.log(String(y)+String(x)+" - "+data_c+" - "+data);
set_aulas_fun(String(y)+String(x),data);
});
}
Use $.get() to send an AJAX request.
$.get("classes_day.php?data=YYYY-MM-DD", function(response) {
console.log(response);
});
BTW, you can add up all the durations in the SQL query instead of using a PHP loop. And you should use a prepared statement to prevent SQL injection.
<?php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT SUM(duration) AS total FROM `task` WHERE `dia` LIKE ?";
$stmt = $link->prepare($query);
$stmt->bind_param("s", $data);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$soma = $row['total'];
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}

Want to select all values but only selecting one

So I am selecting many values from database but there is a row where I can only select one.
Equipamento row has many values but when I open a pop up on click ver mais and it only shows one value
tipo row (tipo = equipamento I have to change that title)
JS:
var idocorrencia;
$(document).on("click","#listagem tr td button",
function(e) {
idocorrencia = $(this).parent().attr("idlista");
$("#listagem caption").text($(this).text());
console.log(idocorrencia);
$.ajax({
type: 'POST',
url: '../php/temp.php',
data: { idoc : idocorrencia },
success: function(data) {
var data_array = $.parseJSON(data);
$("#descricao").empty().append( data_array['descricao'] );
$("#qtd").empty().append( data_array['qtd'] );
$("#sala").empty().append( data_array['sala'] );
$("#tipo").empty().append( data_array['tipo'] );
$("#data").empty().append( data_array['data'] );
$("#hora").empty().append( data_array['hora'] );
}
});
}
);
Here is the php code:
$dados = array();
if(isset($_POST["idoc"])) {
$idoc = $_POST["idoc"];
$sql = "SELECT m.tipo FROM `material` as m INNER JOIN `ocorrencia_detalhe`
as od on m.id = od.id_tipo AND od.id_ocorrencia=$idoc";
$res = mysqli_query($conn, $sql);
while ($r = mysqli_fetch_assoc($res)) {
$tipo = $r['tipo'];
}
$dados["tipo"] = $tipo;
echo json_encode($dados);
And then it displays like this:
<div id="sala"></div>
<textarea id="descricao"></textarea>
<div id="data"></div>
<div id="hora"></div>
<div id="tipo"></div>
<p id="qtd"></p>
You keep overwriting your $tipo variable for each iteration. Append it to an array instead.
You are vulnerable to SQL injection attacks - use a prepared statement with placeholders instead.
$dados = array();
if (isset($_POST["idoc"])) {
$idoc = $_POST["idoc"];
$sql = "SELECT m.tipo
FROM `material` as m
INNER JOIN `ocorrencia_detalhe` as od
ON m.id = od.id_tipo
WHERE od.id_ocorrencia=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $idoc);
$stmt->execute();
$stmt->bind_result($tipo);
while ($stmt->fetch()) {
$dados['tipo'][] = $tipo;
}
$stmt->close();
echo json_encode($dados);
}
Also, see how much easier this code is to read? Properly indented and formatted code is much better to troubleshoot, and for others to read.

How to use javascript if statements within function to populate table

I've created a search page that sends results to a table with the ability to click on a specific record which then opens another page in the desired format.
I'd like to do is be able to open different formatted pages based on the data returned in the search query but I'm having a bit of trouble pulling it all together.
Here's the PHP used to request and retrieve the data from the database, as well as populate it in a table where each record can be selected and used to populate a planner page with all the proper formatting:
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Now the fun part. I want to open different pages based on the information contained in the record. I've got it working for the pkey variable by itself with a single javascript function. However, if I want to open a differently formatted page using the same function using if, else statements, the table only populates with the link page based on the last record compared. Here is my attempt to get the JavaScript with the if, else statements working but it only uses the format of the last record that's compared.
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
} else {
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
How do I get the 'Get Planner' button to open the correctly formatted planner page based on the users specific information?
To make things easier I'd suggest the following:
Do the logic already in php when generating the html-table (and the link).
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
if($rsv) { // thats basicly the same as !=0
$target='../php/plannerR.php'
} else {
$target='../php/planner.php'
}
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td>";
echo "<td>".$row['rank']."</td><td>".$row['ment1']."</td>";
echo "<td><a class='button styleIt' href='".$target."?pkey=".$pkey."&rsv=".$rsv."'>Get Planner</a></td></tr>";
}
If you wanna stick to your js solution (which is more hassle unless you really need it) you can of course go with the solution from my comments that you already successfully implemented (and posted as answer so others can see the implementetion).
Thanks to Jeff I played around a bit with bringing both variables into the function and got it to work. Final code below.
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."','".$rsv."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey, rsv) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
}
else{
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}

loop inside a loop with different mysql in php

Objective: We need that it find registered people and shows which countries had visited like In this image
We need to make a loop that creates php objects (The artists), with its own classes. This objetcs will come from a DataBase (mysql). For each of this objects, we need that it looks in the DataBase which rows are related with it (countries), and make it an php objetc too, with its own classes (Its own design with CSS, HTML)
We already tryed Angular with ng-bind-html so it could read HTML tags and its CSSs, but it only took the first loop, and the second one just didn't appeard. We tryed while inside another while, but I don't know what happens, but it only takes the first one.
The idea to make a loop this way is to hide countries while the user doesn't want to see them. If they click on the artist name, it will shows up the countries. But this is another story, we think we will use CSS for that.
I'll put the code I tryed to use for Angular, just in case someone have an idea with Angular.js.
Thank you very much for reading this. Best Wishes and Best Regards !
$data;
$data['info'] = "";
$id = $_POST['id'];
if (isset($_POST['id'])){
$dsn = 'mysql:dbname=ec;host=localhost;port=3306';
$user = 'root';
$password = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connection = new PDO($dsn, $user, $password, $options); } catch (PDOException $e) {
echo 'Fallo conexión: '. $e->getMessage();
}
$sql = "SELECT ....WHERE artist.artist_id = $i"; //This is to call only artist that the user actually have access to see.
$query = $connection->prepare($sql);
$query->execute();
while($row = $query->fetch()){
$artists[] = $row;
};
if (isset($artists)){
// 1- This is the First loop, it looks for the artist. This is working, barely.
foreach($artists as $art) {
$a = $art['artist_id']
$data['info'] .= "<div class='Main'>
<div class='MainResult'>
{$art['artist_name']}
</div>
<div>
<div class='VisitedPlaces'>
<?php
$sql='SELECT country_name, country_city, country_time FROM country JOIN ...... WHERE... = $a';
$query = $connection->prepare($sql);
$query->execute();
// 2- Here's the second loop, that look for the countries related to the artist. The idea is that once it finish, look for the next artist in the first loop. This one don't works.
while($row = $query->fetch()){
$country = $row['country_name'];
$city = $row['country_city'];
$time = $row['country_time'];
echo '<div class="rslt">
<h2>'.$country.'</h2>
<span>'.$city.'</span>
<span>'.$time.'</span>
</div>';
};
?>
</div>
</div>";
}
echo JSON_encode($data);
}
It's not actually an answer, but some of my suggestions/advices.
First of all code logic is partially not understandable, some variables appears from nowhere. For example: $i and $artists.
Next one - why do you need to return an html-code instead of pure-data?
Third, subjective on me I guess, that the access to the mysql every time is a bad idea.
My vision looks like that:
notice: I haven't test this
<?php
$data = array();
$data['info'] = array(); // changes
$rol = $_POST['id'];
if (isset($_POST['id'])){
$dsn = 'mysql:dbname=ec;host=localhost;port=3306';
$user = 'root';
$password = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connection = new PDO($dsn, $user, $password, $options); } catch (PDOException $e) {
echo 'Fallo conexión: '. $e->getMessage();
die(); // added
}
// what data gets from database?.. idk
// it seems like companies .. what / why / where it used in this code ? unknown
// what is $i ? I guess - artist_id
$sql = "SELECT ....WHERE artist.artist_id = :artist_id";
$query = $connection->prepare($sql);
$query->bindParam(':artist_id', $i, \PDO::PARAM_INT); // suggestion
$query->execute();
$companies = $query->fetchAll(\PDO::FETCH_ASSOC);
// from where we have got this ?
if (isset($countries)){
// 1- This is the First loop, it looks for the artist. This is working, barely.
$artist_ids = array();
// from where this too ? okay, just use it
foreach($artists as $art) {
$artist = array();
// it's just a suggestion about your table scheme
$artist_id = $art['artist_id'];
$artist_ids[] = $artist_id;
$artist['name'] = $art['artist_name'];
$artist['visited_places'] = array();
$data['info'][$artist_id] = $artist;
}
// here is not an actual sql-query, I suggest that country data and artists data are separated
// and sql must be modified to get data from both table at once
$sql = 'select country_name, country_city, country_time, artist_id from country join ... where ... and artist_id in ('.implode(',',$artist_ids).')';
$query = $connection->prepare($sql);
$query->execute();
// I don't know how many rows it will be
// make this safer, get row by row
while ($row = $query->fetch(\PDO::FETCH_ASSOC)) {
$artist_id = $row['artist_id']; // according the new query
$place = array();
$place['country'] = $row['country_name'];
$place['city'] = $row['country_city'];
$place['time'] = $row['country_time'];
$data['info'][$artist_id]['visited_places'][] = $place;
}
} // if $countries
// send back pure-data, your javascript can do anything
echo JSON_encode($data);
} // if $_POST['id']
after all your front-end javascript application will receive a JSON-string, something like this: {"info":{"110":{"name":"Michael Jackson","visited_places":[{"country_name":"JP","country_city":"Tokyo","country_time":"12-sep-1987"},{"country_name":"US","country_city":"New-York","country_time":"03-mar-1988"},{"country_name":"IT","country_city":"Rome","country_time":"23-may-1988"}]}}}
php source:
[info] => Array
(
[110] => Array
(
[name] => Michael Jackson
[visited_places] => Array
(
[0] => Array
(
[country_name] => JP
[country_city] => Tokyo
[country_time] => 12-sep-1987
)
[1] => Array
(
[country_name] => US
[country_city] => New-York
[country_time] => 03-mar-1988
)
[2] => Array
(
[country_name] => IT
[country_city] => Rome
[country_time] => 23-may-1988
)
)
)
)
)

Multiple AJAX functions on one functions page

I'd like to find a way of having a single page in the root of each of my web sections to hold all of the databae queries I'm calling.
I'm using a little script .....
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fn-search-em.php'); ?>;
$("#quick-add").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
.... to do SQL searches that appear as the user is typing. Similar to this ....
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result))
{
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){
$p_mark = 'x';
}
else {
$p_mark = '';
}
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
Echos a list in the form of a JSON array back to the text box and voila, a list. However, the site I'm working on at the moment has about 20 search boxes for various reasons scattered around (user request), does this mean I have to have 20 separate php function pages, each with their own query on, or can a single page be used?
I suspect the java needs modifying a little to call a specific function on a page of multiple queries, but I'm not good with Java, so some help would be greatly appreciated.
I did initially try adding ?action= to the end of the PHP address in the Java script, hoping a GET on the other end would be able to separate the PHP end into sections, but had no luck.
You need to change <?php include('fn-search-em.php'); ?>; to <?php $action = 'mode1'; include('fn-search-em.php'); ?>;.
Then in your fn-search-em.php file, use the $action variable to determine what kind of MySQL query you make.
For example:
if ($action == 'mode1')
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
else
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'mode1' AND deleted = 'no'";
You can do this with by creating a php file with a switch statement to control what code is executed during your Ajax call:
JS:
$.ajax({url: 'ajax.php', method: 'POST', async:true, data: 'ari=1&'+formData,complete: function(xhr){ var availableTags = JSON.parse(xhr.responseText);}});
PHP:
<?php
switch($_REQUEST['ari']){
case 1:
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result)){
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){$p_mark = 'x';}
else { $p_mark = ''; }
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
break;
case 2:
// another SQL Query can go here and will only get run if ARI == 2
break;
}
?>
This allows you to keep multiple AJAX handlers in the same file, you just need to pass the index for the desired handler when you make calls to the PHP file or nothing will happen.

Categories

Resources