So I'm working on quite a big school project and our goal is to show the presence or absence of all students at our school, we have to show this data using chartJS, now we made a query which selects all classes and a foreach-loop runs through the classes and the the query to select the presence and convert it to JSON, I've been working on this function for quite a few days but I just can't seem to make it work...
Here is my QueryManager which activates the query:
public function getAanwezigheid($klassen){
$result = $this->dbconn->query("SELECT klas.code klas, ROUND(
(
SELECT Count(aanwezigheid)
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
WHERE klas.code = '".$klassen."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
AND aanwezigheid = '1'
)
/
(
SELECT Count(aanwezigheid)
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
WHERE klas.code = '".$klassen."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
)
* 100)
as percentage
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
JOIN vak ON college.Vcode = vak.code
WHERE klas.code = '".$klassen."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
GROUP BY klas.code");
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
print json_encode($data);
}
Here is the code which gets the query(the unserialize gets all classes which are available which are class A-F):
if($_GET['action']=='getAanwezigheid'){
header('Content-Type: application/json');
$klas = unserialize($_SESSION['klas']);
/*This loop runs the query for every class which has been found (A-F)*/
foreach($klas as $klas){
$klassen = $klas->getCode();
$result = $q->getAanwezigheid($klassen);
}
}
Here is the result I get:
[][][{"klas":"WFHBOICT.V1C","percentage":"38"}][][][{"klas":"WFHBOICT.V1F","percentage":"67"}]
And I want the result to be this:
[{"klas":"WFHBOICT.V1C","percentage":"38"},{"klas":"WFHBOICT.V1F","percentage":"67"}]
Now I get why I get all the brackets, it's because I loop through data[] every class too, but that's what I'm stuck at. I just need to print 1 JSON result
Any help would be really appreciated.
Related
I have a php function that will get a list of name from column in users database. What I want to do is to get all the values from the column name and insert it into an array.
What I've done from the php side is :
header('Content-type: application/json');
include ('../Core/Initialization.php');
$courseName = $_POST['courseName'];
$semester = $_POST['semester'];
$sql = mysql_query("SELECT DISTINCT `name` FROM `users` WHERE `programme` = '$courseName' AND `semester` = '$semester'") or trigger_error(mysql_error().$sql);
$column = mysql_fetch_assoc($sql);
$arr = array();
foreach($column as $value) {
$arr[] = array('name' => $value['name']); //I have tried it this way but it didn't work when I try to display the values.
}
echo json_encode($arr);//I have tried to remove the array and just json_encode($column). I have successfully print out the first values, but fail to print out the next values collected from the column.
The js function that will process/print out the name:
function nameProcess(data) {
alert(data.name); //This will only display the full values from the first(?) index
nameArray = data.name;
for (var i=0; i < nameArray.length; i++) {
alert(nameArray[i]); //But, this loop only displays one character each time of the alert. Example: Each character from the word "Hello" will show up one by one as alert.
}
}
});
Is there any better way to do this? What I want to do is, exporting all values from column name into an array, and iterate each of its value as an option of a a select box. But for now, how do I fix the problem?
First of all, don't use mysql_* functions as they are deprecated and
removed totally PHP 7.
Back to your question, you can fetch mysql multi-dimensional array with MySQL only with loop.
Corrected code:
$sql = mysql_query("SELECT DISTINCT `name` FROM `users` WHERE `programme` = '$courseName' AND `semester` = '$semester'") or trigger_error(mysql_error().$sql);
$res = mysql_query($sql); // Missing this.
$column = ;
$arr = array();
while ($value = mysql_fetch_assoc($res)) {
$arr[] = $value['name'];
}
echo json_encode($arr);
Note: The PHP MySQL commands you are using are deprecated. It's recommended to use the PDO class (as MySQLi is also deprecated).
It depends on the pre-processing you are performing, but from what I can see based on the information you provided, you are passing each element of the returned data through to nameProcess.
So a return data of
array(
array('name' => 'John Smith',
array('name' => 'Jane Doe',
array('name' => 'Foo Bar'
);
Will require the nameProcess function to be invoked 3 times.
So each time you go through to define
nameArray = data.name;
nameArray becomes a string since data.name is 'John Smith' the first invoke, 'Jane Doe' the second invoke, and 'Foo Bar' the last invoke.
So when you call
alert(nameArray[i]);
It's calling the character at position i within the string.
nameArray[0]; // 'J'
nameArray[1]; // 'o'
nameArray[2]; // 'h'
nameArray[3]; // 'n'
// etc
If you change it to:
function nameProcess(data) {
alert(data.name);
nameArray = data.name;
alert(nameArray);
}
It will alert the full name.
The way around this would be to ensure that you pass the JSON parsed data to the function without the pre-processing, in which case your original code should work if you change it to:
function nameProcess(data) {
alert(data.name);
nameArray = data.name;
for (var i=0; i < nameArray.length; i++) {
alert(nameArray[i].name);
}
}
I tried to build an ajax search bar. It works fine with a single keyword but I can't manage to make it work with 2 keywords...
I was thinking about parsing the data in the input field but my knowledge is limited and I didn't manage to find the solution.
Any ideas?
In my main.js I get the data from the input like this:
var kwVal = $(this).val();
if (kwVal.length < 3){
$(".clothes-container").html("");
}
else {
$.ajax({
"url": "ajax/getclothes.php",
"type": "GET",
"data": {
"kw": kwVal
}
})
And this is my sql request
$sql = "SELECT title, description, picture
FROM outfit
WHERE type LIKE :keyword OR
color LIKE :keyword OR
brand LIKE :keyword OR
material LIKE :keyword";
Thanks a lot.
Something like this? Of course, all the SQL literals and strings must be properly escaped (especially the $keyword).
// keywords extracted from user's input
$keywords = array('blue', 'jeans');
// columns, that You want to match against
$columns = array('type', 'color', 'brand', 'material');
// we build the condition for each keyword
$word_conditions = array();
foreach ($keywords as $keyword) {
$conditions = array();
foreach ($columns as $column)
$conditions[] = $column.' LIKE \'%'.$keyword.'%\'';
$word_conditions[] = '('.implode(' OR ', $conditions).')';
}
// we build the query, that requires every item to have all the keywords
$query = 'SELECT * FROM ... WHERE '.implode(' AND ', $word_conditions);
Suppose your keywords are saperated by 'Space' like "ABC DEF GEH".
than on server you can do is,
$keywords = explode(" ", $_POST['data']); //Make it array;
$string = implode(",", $keywords);
$sql = "SELECT title, description, picture
FROM outfit
WHERE type in (".$string.") OR
color in (".$string.") OR
brand in (".$string.") OR
material in (".$string.")";
Recently I have been trying to make an auto-complete search.
I looked up some infos and figured out that there is a way to
use PHP variables at the source... but however when I try to get a
list of the places name, I get the results into an array
$db = new OBJ_mysql($config_budapest);
$places = array();
//- getting the list of the cities
$autocomplete= $db->query("SELECT DISTINCT Helyseg FROM M_munka WHERE Publikus = '1' AND Aktiv = 1 AND Jovahagyott = 1");
$autocomp_q= $autocomplete->fetchAllArray();
$writeauto = json_encode($autocomp_q); /* ECHO ALL THE RESULTS */
//array push
array_push($places,$autocomp_q);
<script type="text/javascript">
$(function() {
var availableClients = [<?php echo json_encode($places);?> ];
$("#tags").autocomplete({
source: availableClients,
});
});
</script>
Result:
Updated Result:
As far as I can see in your code, $places is an array of your query result. It seems you are creating an array of arrays (array with other arrays inside it)
Did you try to assign the query result to $places, something like this:
$db = new OBJ_mysql($config_budapest);
//- getting the list of the cities
$autocomplete= $db->query("SELECT DISTINCT Helyseg FROM M_munka WHERE Publikus = '1' AND Aktiv = 1 AND Jovahagyott = 1");
$autocomp_q= $autocomplete->fetchAllArray();
$writeauto = json_encode($autocomp_q); /* ECHO ALL THE RESULTS */
$places = $autocomp_q;
Hope it helps!
this is the code i have, actually i am inserting a array in json encode data and getting back via jquery.
$list_type_query = "select * from assettype";
//the asset type table contains (id & type) column
$query = mysqli_query($conn, $list_type_query);
while($r = mysqli_fetch_array($query)){
$result_value = array("Status" => "haslist", "list" => $r);
}
this is jquery side.
case "loaddefaultmodel":
var showtype = $('#sh');
var showvalue = '<span>'+data['list']+'</span>';
showtype.html(showvalue);
break;
$('#sh') is a div i need to show all type content in the span inside the div.
if i use the data['list'][0]['type'] i getting a object 0 value.
how to show all value one by one dynamically in div.
I think the issue in your php code.
Because in every loop, the $r just get every current index data, And $result_value just get current index data.
You can try this...
$list_type_query = "select * from assettype";
//the asset type table contains (id & type) column
$query = mysqli_query($conn, $list_type_query);
$all_data = array();
while($r = mysqli_fetch_array($query)){
$all_data[] = $r;
}
$result_value = array("Status" => "haslist", "list" => $all_data);
I have fetched data from MySQL and echoed JSON encoded data as follows:
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$myjsons[$i] = json_encode(array($row));
$i++;
}
echo json_encode($myjsons);
And I have a Javascript function that reads the string and shows it in a text box:
if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {
$("#txtfld").val(data);
var arr =data.slice(1);
var user_arr = arr.slice(0,-1);
var json = user_arr,
obj = JSON.parse(json);
alert(obj.user_id);
$("#resultTXT").val(obj.user_id);
},'json'
);}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}
The problem is that txtfld shows the string as [{"user_id":"2790","fre.....tst":""}] and resultTXT shows nothing because of the two [ ]. I have tried to remove them using slice but it seems that the slice doesn't work on JSON strings. What else can I do to remove [ ] so that the resultTXT shows the user_id?
Thanks
you convert the array 2 times to json.
php doesn't need the a index for the next array element
i would also add the correct header "application/json"
$row is already a associative array
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
while ($row = mysql_fetch_assoc($result)) {
$myjsons[] = $row;
}
header('Content-type: application/json');
echo json_encode($myjsons);
this gives you a proper formatted json
to access your json in javascript u do:
var obj=JSON.parse(json);
i assume that your mysql returns a list of orders or users [{"user_id":1},{"user_id":2}] so if you want to access the first user's id:
obj[0].user_id
but if i misunderstand u could post more info about your json.