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);
Related
So I am trying to send the "id" of a selected row in datatable in javascript to a php page so I could delete it from database.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0] });
the variable "ids" is sent by post method
$.post( "deleterow.php", { v1: ids });
but it didn't worked so i try to see the response from post method and it says
"notice array to string conversion in C on line ... "
the line is of php page where i am writing the delete query
$id = $_POST["v1"];
$query = "DELETE FROM `package` WHERE `id` = '$id'";
The whole php page works fine when trying with other values.
Because you send an array here:
$.post( "deleterow.php", { v1: ids });
so v1 contains an array of elements. But in your php code you treat it as a single element:
$id = $_POST["v1"];
Hence the notice array to string conversion.
If you send an array of elements, you have to get it as an array and treat is as an array. To create a correct SQL string you should append each ID, like this:
$ids = json_decode($_POST["v1"]);
$query = "DELETE FROM `package` WHERE";
$first = true;
foreach ($ids as $id) {
if ($first) {
$first = false;
} else {
$query += " OR";
}
$query += " `id` = '$id'"
}
This way you loop the array and append a id = ID for each array element.
Now, this is important, this code is prone to SQL injection, a really bad security problem. Read this to get more info about this: How can I prevent SQL injection in PHP?
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);
}
}
This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 1 year ago.
I've spent a couple of hours looking through several the similar answers before posting my problem.
I'm retrieving data from a table in my database, and I want to encode it into a JSON. However, the output of json_encode() is only valid when the table has one single row. If there is more than one row, the test at http://jsonlint.com/ returns an error.
This is my query:
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
$rows['data'] = $r;
//echo result as json
echo json_encode($rows);
}
That gets me the following JSON:
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
When I run the test at http://jsonlint.com/, it returns this error:
Parse error on line 29:
..."No comment" }}{ "data": {
---------------------^
Expecting 'EOF', '}', ',', ']'
However, if I only use this first half of the JSON...
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
... or if I only test the second half...
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
... the same test will return "Valid JSON".
What I want is to be able to output in one single [valid] JSON every row in the table.
Any suggestion will be very much appreciated.
The problem is you're spitting out separate JSON for each row, as opposed to doing it all at once.
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
// $rows[] = $r; has the same effect, without the superfluous data attribute
$rows[] = array('data' => $r);
}
// now all the rows have been fetched, it can be encoded
echo json_encode($rows);
The minor change I've made is to store each row of the database as a new value in the $rows array. This means that when it's done, your $rows array contains all of the rows from your query, and thus you can get the correct result once it's finished.
The problem with your solution is that you're echoing valid JSON for one row of the database, but json_encode() doesn't know about all the other rows, so you're getting a succession of individual JSON objects, as opposed to a single one containing an array.
You need to change your PHP code into something like this:
$result = mysql_query($query);
$rows = array();
//retrieve every record and put it into an array that we can later turn into JSON
while($r = mysql_fetch_assoc($result)){
$rows[]['data'] = $r;
}
//echo result as json
echo json_encode($rows);
I think you should do
$rows = array();
while($r = mysql_fetch_assoc($result)){
$rows[]['data'] = $r;
}
echo json_encode($rows);
echo should be placed outside of the loop.
I was trying the same in my PHP, so I came whit this...
$find = mysql_query("SELECT Id,nombre, appaterno, apmaterno, semestre, seccion, carrera FROM Alumno");
//check that records exist
if(mysql_num_rows($find)>0) {
$response= array();
$response["success"] = 1;
while($line = mysql_fetch_assoc($find)){}
$response[] = $line; //This worked for me
}
echo json_encode($response);
} else {
//Return error
$response["success"] = 0;
$response["error"] = 1;
$response["error_msg"] = "Alumno could not be found";
echo json_encode($response);
}
And, in my Android Class...
if (Integer.parseInt(json.getString("success")) == 1) {
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
if (!value.equals(1)) {
JSONObject jsonArray = (JSONObject) value;
int id = jsonArray.getInt("Id");
if (!db.ExisteAlumo(id)) {
Log.e("DB EXISTE:","INN");
Alumno a = new Alumno();
int carrera=0;
a.setId_alumno(id);
a.setNombre(jsonArray.getString("nombre"));
a.setAp_paterno(jsonArray.getString("appaterno"));
a.setAp_materno(jsonArray.getString("apmaterno"));
a.setSemestre(Integer.valueOf(jsonArray.getString("semestre")));
a.setSeccion(jsonArray.getString("seccion"));
if(jsonArray.getString("carrera").equals("C"))
carrera=1;
if(jsonArray.getString("carrera").equals("E"))
carrera=2;
if(jsonArray.getString("carrera").equals("M"))
carrera=3;
if(jsonArray.getString("carrera").equals("S"))
carrera=4;
a.setCarrera(carrera);
db.addAlumno(a);
}
}
} catch (JSONException e) {
// Something went wrong!
}
}
I must have spent 15 hours on this issue. Every variation discussed above was tried. Finally I was able to get the 'standard solution' working. The issue, very oddly, appears to be this:
When the interval is set beyond 14 hours, json appears to be unable to parse it. There must be a limit to JSON.
$sql= "SELECT cpu_name, used, timestamp FROM tbl_cpu_use WHERE timestamp>(NOW() - INTERVAL 14 HOUR) ORDER BY id";
$result=mysql_query($sql);
if ($result){
$i=0;
$return =[];
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$rows[] = $row;
}
echo json_encode($rows);
}else{
echo "ERROR";
}
I have a mysql database table called 'employees'
It has 3 columns named 'id', 'name' and 'salary'
I have html/php web page with text boxes called id and name.
I want to load 'id' and 'name' of the employee who has the maximum salary, from database to these text boxes.
<?php
//Defining constants for database connection best to store in seperate file and include that file
const DB_HOST = 'SERVER';
const DB_USER = 'USER';
const DB_PASS = 'PASSWORD';
const DB_NAME = 'php_mysql_login_system';
//Connecting to the database -- best use pdo
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$sql = " SELECT * from `employees` "; // query data from databse -- alhough I suggest you use pdo
$result = $mysqli->query($sql);
//Looping through each results
foreach ($result as $value) {
// Store the employess salary and name in an array say employee['name'=>salaray] -- name as key and salary as value
}
$maximumSalary = max(//array of the employee i.e the one you have made above employee[]);
//after getting the maximum value use array_keys(array,value) to get the employee name
$employeeName = array_keys($employee,$maximumSalary);
}
?>
A sample code to get you started hope this helps you although this code might not be following best practise it is for you to get started with at least something as I think you are having trouble getting started.
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.