Creating a json array using concat with MySql - php

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('...')"

Related

creating json by data from mysql db and variable data

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

Convert sql result (object) to string variable for future input into sql table (I do not want to echo the result)

I have read most of the questions here and read the php manual in regards to the problem of converting an sql result to a string, however none of them is working for me. The examples given I understand, however they are echoing the sql results, I do not want the result to be echoed, I just want it to be stored in a variable so I can immediately insert it into a next sql table.
This is my code:
$cnt_fips = mysqli_query($con, "SELECT cc_fips FROM location2 WHERE location_name = '$cnt'");
$row = mysqli_fetch_assoc($cnt_fips);
These are the codes I have used to convert to string but failed with
$myStr = !is_array($row) ? trim(addslashes($row)):'';
and
$myStr = (string)$row;
and
$myStr = print_r($row,true);
and also
$myStr = (string)$row;
And insert into the table below
$query2 = mysqli_query($con, "INSERT INTO location3 VALUES ('','$myStr')");
$row is always an array with column names as the keys, use:
$myStr = $row['cc_fips'];
Also, I'm pretty sure you can do that all in one insert with a sub-select (though maybe not if a row with $cnt doesn't exist). If so, maybe someone will post it.

PHP function issues with array

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.

how to construct a mysql query that puts quotes around strings but not numbers?

i have use function for inserting data to my sql.
the data is
function mysql_insert($table, $arr){
if($arr!=''){
$values = array_map('mysql_real_escape_string', array_values($arr));
$keys = array_keys($arr);
$q=('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
//$res = mysql_query($q)OR die(mysql_error());
return $q;
}else{
return false;
}
data and query is came from :
if($crud=='insert'){
$field= array( 'col1' => 'apel',
'c0l2' => 'box1',
'col3' => 200,//integer Quantity
);
$data=mysql_insert('wh',$field);}echo json_encode($data);
and result is
= "INSERT INTO wh (col1,c0l2,col3) VALUES ('apel','box1','200')"
that col3 have value as string. i need that col3 as integer.
what wrong with this code?
In the following code :
implode('\',\'', $values)
the implode is converting the array of values to a string, separating each value by ','
and before and after the implode code, there are also quotes, which will wrap all your values with ' make it look like all the values are strings
but like octern i don't see why the query would fail, even if you are wrapping integer values with ' if the correct data type is selected in the database it should work fine
If you still want to use quates around the string but not around the integer or boolean
try the php function json_encode()
example here: http://codepad.org/Hpvzjnjc
This is happening because the command implode('\',\'', $values) is telling it to turn the array $values into a string, with single quotes and commas between each element. If you want to not put quotes around numbers, you'll need to iterate over $values with a more specific function.
However, it doesn't actually matter. If you give MySQL a string containing a number for a numeric field, it will just convert it to a number of the appropriate type. You can leave it as-is and everything should work.

How do i parse the the value from a string in the function call?

i have function which is something like this
function multiple_delete($entity1,$entity2,$entity2) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $entity1;
echo $entity2;
echo $entity3;
}
and my function call is
multiple_delete('$row[\'pic_title\']', '$row[\'pic_brief\']', '$row[\'pic_detail\']');
keeping in mind the three value which i am passing through the parameter is the entity name of particular table.
now this function will print it as the string i.e ($row['pic_title'], $row['pic_brief']', $row['pic_detail']) and hence not parse it as the value which i want it to do. if it parse it as the value then i will be able to get the records from the database. i have tried with the combination of single quotes, doubles, with concatenation operator etc. is there any way i tell the script that do not parse it as the string instead treat it as it have been declared to fetch the value from database. does php have any function for this ? or i am going wrong with the logic.
if i skip the parameters and declare in the functions something like this.
echo $row['pic_title'];
echo $row['pic_brief'];
echo $row['pic_detail'];
it works perfectly fine . why is that when i try to achieve the same thing with the help of parameter it refuses to fetch the value from the database, and instead it returns the same declared string from the function call.
Please do not tell me that i dont need that parameter, i need it because i want it to perform the dynamic data manipulation, with regard to different tables and different table entities. and the above function is just the demonstration of my problem not the exact function. if you want to have a look at the exact function you can check here.
What is wrong with my function?
thank you
Just pass the names of the columns:
multiple_delete('pic_title', 'pic_brief', 'pic_detail');
Then you can use them to access the corresponding values in the row array by using the names them as keys:
function multiple_delete($entity1, $entity2, $entity3) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[$entity1];
echo $row[$entity2];
echo $row[$entity3];
}

Categories