loop inside a loop with different mysql in php - javascript

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
)
)
)
)
)

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;
}

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.

i can't put the input data into the database

this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe

Autocomplete json_encode return by column

I'm using the autocomplete UI for my search box. Below is my php code:
<?php
include 'connect.php';
if (isset($_GET['term'])) {
$value = $_GET['term'] . '%';
$return_arr = array();
$stmt = $conn->prepare("SELECT * FROM jobs WHERE jobname LIKE ? or formtype LIKE ?");
$stmt->bind_param("ss", $value, $value);
$stmt->execute();
$stmt->bind_result($entryid, $jobnumber, $jobname, $formtype, $date);
while ($stmt->fetch()) {
$return_arr[] = $jobname;
$return_arr[] = $formtype;
}
echo json_encode($return_arr);
}
?>
Everything works perfectly fine. But I kind of want for the while statement to return all $jobname values first before the $formtype values. In short, I want the values to be returned by column and not by row. I'm not sure how it is possible because I tried putting them inside do while and foreach statements but both didn't work for me.
Also for some reason, when I create another echo statement, the:
echo json_encode($return_arr);
stops working.
. But I kind of want for the while statement to return all $jobname values first before the $formtype values.
Build two arrays and then merge them:
$ar1 = [];
$ar2 = [];
while($stmt->fetch()) {
$arr1[] = $jobname;
$arr2[] = $formtype;
}
$return_arr = array_merge($arr1, $arr2);
Also for some reason, when I create another echo statement, the:
echo json_encode($return_arr);
stops working.
Because autocomplete expects json object and you want to try give him json object and something else

using phpfile output inside js file file as variable

Recently I am learning single page application, but I got a problem, the project I am working on is inside a folder that contain many folders, php js are folders in side the main folder, and each contain its type of files, the problem is that one of the php file called getmax.php gives me the maximum id ,I want to use this max(id) in a js file called module.js in order to give the new module the next id , the module.js should gives this id to another php file called insert.php ,the connection between the module.js and insert.php is working properly if I set the id manually . but I could not figure out how can I make it use the max(id) from the getmax.php file.
note: I noticed lately I'm using MySQL and I should used mysqli I will fix it later.
the getmax.php is:
<?php
// alle relevanten Tabellen abfragen und als json zurückgeben.
$json["status"] = "running";
$details[] = "started get_tables ";
// Include confi.php
include_once('confi.php');
//var_dump($_POST);
$request_body = file_get_contents('php://input');
// first store the given set of data to keep it for future analysis
$statement = "INSERT INTO tbl_archive (content) VALUES ('$request_body' );";
mysql_query($statement);
$input = json_decode($request_body, true);
// now check if valid user
$user = $input["user"];
$username = $user["username"];
$password = $user["password"];
if($password and $username){
$mySQLstring = "SELECT username, password, id, create_user FROM tbl_user where username = '$username' ;";
$json["statement"][] = $mySQLstring;
$qur = mysql_query($mySQLstring);
//var_dump ( $qur );
if ($qur){
$max = mysql_fetch_assoc($qur);
}
if ($max){
$json["max"] = $max;
if ($max["password"] == $password){
$json["username"] = $username;
$json["id"] = $max["id"];
$json["create_user"] = $max["create_user"];
$json["status"] = "ok";
$tables = array("class", "class_user", "module", "module_class", "module_user", "rating", "student", "student_class");
//$tables = array("class");
foreach($tables as $table){
if ( $table == 'module' ){
$statement ='SELECT create_user, MAX(id) FROM tbl_'.$table;
//$statement .= ' GROUP BY create_user' ;
$statement .= ' WHERE create_user = 19 ' ;
$qur = mysql_query($statement);
if ($qur){
while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
//var_dump($r);
//echo (json_encode($r));
$result[$table][] = $r;
}
}
}
}
$json = array("status" => "ok", "data" => $result);
}
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
PHP and JS are run on the server and client respectively, and as such you cannot call methods/functions of one from the other. AJAX exists to pass values between JS and serverside code.

Categories

Resources