I have data from MySQL database and data from base64 file out of database
I want to combine them so i can have one JSON data with both
$PaFile="JVBERi0xLjcKMS.....";
$NaFile="JVBERi0xLjvvm.....";
$sqlRun = mysqli_query($conn, "SELECT laimCode, laimYear, laimMonth FROM laim_folio");
$row = mysqli_fetch_assoc($sqlRun);
$json_array[] = $row;
$jasondata = json_encode($json_array[]);
What i expect as output is
[{
"laimCode":"1234",
"laimYear":"2021",
"laimMonth":"11",
"PaFile":"JVBERi0xLjcKMS.....",
"NaFile":"JVBERi0xLjvvm....."
}]
If i put these two variable in SQL as static column with value i can get the result i want
But is there way to combine them outside SQL ?
Like extends array with two extra field and then convert to JSON
You can either add them to the array after fetching the data from the database and before adding into the overall array....
$row = mysqli_fetch_assoc($sqlRun);
$row['PaFile'] = "JVBERi0xLjcKMS.....";
$row['NaFile'] = "JVBERi0xLjvvm.....";
$json_array[] = $row;
$jasondata = json_encode($json_array);
Or add the values to the SQL so they become part of the result set. So the value is just a literal and the alias becomes the column name...
SELECT laimCode, laimYear, laimMonth,
"JVBERi0xLjcKMS....." as PaFile,
"JVBERi0xLjvvm....." as NaFile
FROM laim_folio
I have recently used this concat operator to join columns in JSON.
select concat('{"laimCode":',laimCode,',"laimYear":',laimYear,',"laimMonth":',laimMonth,',"PaFile":"JVBERi0xLjcKMS.....", "NaFile":"JVBERi0xLjvvm....."}') as json FROM laim_folio
Related
How can I list names of tables in sql database and the table columns for the each table and then get a json encoding of the results in PHP?
Here is code to display tables:
$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) {
// go through each row that was returned in $result
echo($table[0] . "<BR>"); // print the table that was returned on that row.
}
You could create an array/object and add the data to it. To get a json result just call json_encode on the array/object.
Here is what I would do:
// Create an object
$results = new stdClass();
// Get all tables
$result = mysql_query("show tables");
// Always check if the query returned anything to prevent possible errors
if(mysql_affected_rows() > 0) {
// Loop through each table
while($table = mysql_fetch_assoc($result)) {
// Get the columns in the table
$resultColumns = mysql_query("show columns from ".$table);
if(mysql_affected_rows() > 0) {
// Columns found. Create a new property in the object and assign the columns to it
$tableColumns = mysql_fetch_assoc($resultColumns);
$results[$table] = $tableColumns;
}
else {
// No columns found. Create a new property in the object and assign a blank array.
$results[$table] = [];
}
}
}
Now we can return that data as a json with json_encode($results).
http://php.net/manual/en/function.json-encode.php
As a side note, I would look to use mysqli, not mysql (as it is now depreciated). The syntax for it is basically exactly the same, but you need to pass the connection variable as the first parameter in most cases. So it would be useful to use create a database/connection class and call to those methods, instead of calling mysql or mysqli functions directly.
See here: https://www.w3schools.com/php/php_ref_mysqli.asp
And here (an example): https://www.johnmorrisonline.com/simple-php-class-prepared-statements-mysqli/
Note: This is pseudo code and not tested but should be okay. Let me know if you need any help with it.
I did a SELECT query on MySQL and get this as result.
The problem is how can I remove the 2nd duplicated results at for instance we use the 1st item in the list. "0":"1" is a duplicate for "id":"1" I would rather use "id" instead of "0" as the key later on the the app. How could I remove this to simplify the results. I do notice that the "0" means the 1st column as the successive columns does add up by 1.
Here's the $query I run.
SELECT id FROM clubsinformation WHERE :comparisonTime < updateTime
This is caused by most likely the fetching mode, you need to fetch it by associative indices only because right now you're including both associative and numeric index fetching:
No matter what DB API you got, MySQLi or PDO, just set it to associative.
So that it turn it doesn't include the numeric indices, only the column names as keys:
So this would roughly look like in code (from looking at your query placeholders, it seems PDO, so I'll draft a PDO example):
$data = array(); // container
$query = 'SELECT * FROM clubsinformation WHERE :comparisonTime < updateTime';
$select = $db->prepare($query);
$select->bindValue(':comparisonTime', $comparisonTime);
$select->execute();
while($row = $select->fetch(PDO::FETCH_ASSOC)) { // associative
$data[] = $row; // only includes column names
}
// then finally, encode
echo json_encode($data);
// OR SIMPLY
// $data = $select->fetchAll(PDO::FETCH_ASSOC); // associative
// echo json_encode($data);
That fetching is by way of PDO API. If you're using MySQLi you can still use the basic idea.
I have a postgres table with four columns labelled dstart which is date data type,
dend which is also a date data type, dcontract which is a date data type and id which is a integer. I am trying to run a php code to get the data using an array and use it in the body of my application. But when I test the array and try to echo some values... My browser just displays the word array... Is there anyway I can be able to retrieve the data or fix this code? Please see code below
<?php
function getLiveDate($campid)
{
global $conn,$agencies;
$return=array(
'livedate'=>'',
'campid'=>'',
'enddate'=>'',
'dateContract'=>'',
);
$sql = "SELECT id, dcontract, dstart, dend
FROM campaigns
WHERE id = '".$campid."' ORDER BY dstart DESC LIMIT 1";
$r = pg_query($conn,$sql);
if ($r)
{
$d = pg_fetch_array($r);
if (!empty($d))
{
$return['livedate'] = $d['dstart'];
$return['campid'] = $d['id'];
$return['enddate'] = $d['dend'];
$return['dateContract'] = $d['dcontract'];
}
}
#pg_free_result($r);
return $return;
}
I am pretty sure, your array $d is "multi-dimensional" and pg_fetch_array() returns an array of arrays, because the result of SQL queries in general may contain multiple rows. You limited it to one row, but you certainly get the correct values by assinging $return['livedata'] = $d[0]['dstart']; or $return['livedata'] = $d['dstart'][0]; and so on (I am not familiar with that particularly function for I usually use MySQL instead of Postgre).
Besides, try echoing your data by means of print_r() instead of echo.
The $return variable is an array, if you want shows the content, you must use print_r or var_dump not echo.
I'm creating a json array from MySql data using concat like this:
$id = '5705';
$sql = 'select concat("{""type:""colName"",""id"":""$id""}") as myJson from table where etc.;
$stmt = $conn->prepare($sql);
What's happening is, instead of getting data from colName from the table and the value of $id, I'm getting the result as it is in $sql. How do I break out of it and get colName and $id's value?
Current Result
{""type:""colName"",""id"":""$id""}
Desired Result
{""type:""novice"",""id"":""5705""}
//Here novice is data from colName, and 5705 is the value of $id
Please DON'T DO THAT. Trying to format data into JSON in your SQL will be fragile as encoding things into JSON is subtly more tricky that you would expect and you will inevitably get it wrong.
You should use the json_encode function in PHP. It will work reliably whereas your code will almost certainly break.
$dataArray = array();
while($statement->fetch()){
$data = array();
$data['type'] = $typeColumn;
$data['id'] = $id;
$dataArray[] = $data;
}
json_encode($dataArray, JSON_HEX_QUOT);
Also, formatting data to send to a client really shouldn't be part of an SQL query.
You need a better concatenation either in query and php
'select concat("{""type:"",colName,"",""id"":""'.$id.'""}")
Despite it is not really needed you could surround column name with backticks `
Your variables inside your string are not substituted with their values, as you got single quotes. Double quoted strings will expand variables with their values
Thus, you could invert your quotes, like this, in order to get the actual values of your variables:
$sql = "select concat('...')"
I have a query that is sent to my SQL database from PHP. It looks something like this:
$result = mysql_query("SELECT ...");
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);
I ultimately return the json_encoded result to my Java application (Android, actually) so that I can pick apart the pieces and put them into a nice Java object.
I have come to a point where I need some more data to come from this query, and I don't know how to get it. Is there a way for me to give myself the results of ANOTHER query, and inject it into this json_encoded result? Like basically run another query, and append it to the $r on each iteration of the loop and have it "seem" as if it was another column returned from the original queries select? I just don't know how to handle this $rows[] array.
Let me know if my question is not clear.
Add mutiple levels to your PHP array:
$data = array();
$data['part1'] = 'data from query 1';
$data['part2'] = 'data from query 2';
echo json_encode($data);
then simply refer to those sub-arrays in your client-side code.