Outputting concatenated data from mysql to json as json object - php

This is my database:
Am trying to get all from_id which to_id is 4 to a json object where ill be able to show all messages from a from_id in a stack sorted by their different time_sent
I have tried:
CODE:
DATABASE QUERY CLASS(THIS IS IN THE DBASE CLASS)
public function query($sql){
$this->_last_query = $sql;
$result = mysqli_query($this->_conndb, $sql);
$this->displayQuery($result);
return $result;
} // end of query
public function displayQuery($result){
if(!$result){
$output = "database query failed :". mysqli_error($this->_conndb);
$output .= "last sql query was: ".$this->_last_query;
die($output);
}
else{
$this->_affected_rows = mysqli_affected_rows($this->_conndb);
}
} //End of query results
public function fetchAll($sql){
$result = $this->query($sql);
$out = array();
while($row = mysqli_fetch_assoc($result)){
$out[] = $row;
}
mysqli_free_result($result);
return $out;
}
MESSAGE CLASS:
private $_table = 'messages';
public function getadminMessage(){
$sql = "SELECT group_concat(messg, time_sent, from_id) as from_id from {$this->_table} where to_id = 4 group by from_id";
return $this->db->fetchAll($sql);//IN THE DBASE CLASS ABOVE
}
In the file getadminmessage.php
$message = new Message();
$results = $message-> getadminMessage();
echo json_encode($results);
I then use getjson
$.getJSON("http://127.0.0.1/tum_old/custom/php/getadminmsg.php",
function(response){
console.log(response);
});
On my log i get
The data seems group concatenated but i would also like the various messages to be in object form that is the messages to be displayed as objects such that i can easily do:
data.object[0].from_id[0].msg to get TRUE LOVE as the message
scais::::

for select you need
$sql = "SELECT group_concat(messg) as msg, time_sent, from_id
from {$this->_table} where to_id = 4 group by from_id";
for server side you need json_encode the array
public function fetchAll($sql){
$result = $this->query($sql);
$out = array();
$cnt =0;
while($row = mysqli_fetch_assoc($result)){
$out[$cnt]['msg'] = $row['msg'];
$out[$cnt]['time_sent'] = $row['time_sent'];
$out[$cnt]['from_id'] = $row['from_id'];
$cnt++;
}
mysqli_free_result($result);
return json_encode($out);
}

Try this:
public function fetchAll($sql){
$result = $this->query($sql);
$out = array();
while($row = mysqli_fetch_assoc($result)){
$out[] = array(
'id' => $row['id'],
'from_id' => $row['from_id'],
'to_id' => $row['to_id'],
'msg' => $row['messg']
);
}
mysqli_free_result($result);
return json_encode($out);
}

Try removing the group by statement and building a new multi dimensional array instead with the result rows before you output it as a json encoded string. See example below
$out = array(
'messages' => array(),
);
while($row = mysqli_fetch_assoc($result)){
$out['messages'][$b['from_id']][] = array(
'msg' => $b['message'],
'time_sent' => $b['time_sent'],
);
}
return $out;
The keys in your $out['messages'] array will be your from_id values. Each entry will be arrays of messages from each id, so in your javascript you should be able to iterate over these

Related

How modify to PHP SQL SELECT query to display message depending on if data is found

I have the following SELECT query that shows data depending on if it exists in the mySQL table.
Right now if it does it will display all of the records found, If not it will just display nothing.
I would like to make it display if the record is found
{"error":false}
and If the record is not found
{"error":true}
The following is what I have so far:
$sql = "SELECT field1,field2
from Table1 WHERE field3 = 'Dog' ";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// Create temporary connection
$resultArray = array();
$tempArray = array();
// Look through each row
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
mysqli_close($con);
How can this be achieved?
you need to initialize an array with a default value, then change the value if the records are found
$sql = "SELECT field1,field2
from Table1 WHERE field3 = 'Dog' ";
$resultArray = ['error' => true];
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// Create temporary connection
$tempArray = array();
// Look through each row
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
$resultArray['error'] = false;
}
echo json_encode($resultArray);
mysqli_close($con);
You can do something like that:
$return = [
'error' => true
];
$sql = "SELECT field1,field2
from Table1 WHERE field3 = 'Dog' ";
$result = mysqli_query($con, $sql);
if($result && $result->num_rows > 0){
$return['error'] = false;
}
mysqli_close($con);
echo json_encode($return);

cannot insert query result into file

I try to insert result of query into some file.
The file is created but it contain nothing.
I check the query result and its working, i receive a result data.
here is my controller code :
$members_nik = array();
$members_nik = select_config_by('member', 'member_nik', 'WHERE 1=1');
file_put_contents("data.txt", implode(', ', $members_nik));
here is my function code :
function select_config_by($table, $obj, $where){
$query = mysql_query("SELECT $obj as result FROM $table $where");
$row = mysql_fetch_array($query);
$result = $row['result'];
return $result;}
You are returing a string from the select_config_by function but then trying to implode it as if it were an array.
Now assuming you want to return all the results and save them in your data.txt, change the function to this:
function select_config_by($table, $obj, $where)
{
$result = mysql_query("SELECT $obj as result FROM $table $where");
$temp = array();
while ($row = mysql_fetch_array($result))
{
$temp[] = $row['result'];
}
return $temp;
}

I cannot populate an array with sql query data to export it as json object in php

I am new with php, I try to call the following function in order to populate an array of previously inserted data in mysql, but I get null.
function GetBusiness($con, $email)
{
$query = "SELECT * from Business WHERE B_EMAIL ='".$email."'";
$res = mysqli_query($con,$query);
$result_arr = array();
while($row = mysqli_fetch_array($res))
{
$result_arr[] = $row;
}
return $result_arr;
}
and then I try to construct my json object as..
$result_business = array();
$result_business = GetBusiness($con, $email);
$json['result'] = "Success";
$json['message'] = "Successfully registered the Business";
$json["uid"] = $result_business["id"];
$json["business"]["name"] = $result_business["name"];
$json["business"]["email"] = $result_business["email"];
but for even if the data are inserted successfully the part of $result_business is null, why I get null? I my $query typed wrong?
thank you
The problem is, your function GetBusiness returns a multi-dimensionnal array, you can use this one instead :
function GetBusiness($con, $email)
{
$query = "SELECT * from Business WHERE B_EMAIL ='".$email."'";
$res = mysqli_query($con,$query);
return mysqli_fetch_array($res);
}
Also, you must use the MySQL columns that you selected to access the data of the rowset. Something like
$json["uid"] = $result_business["B_ID"];
$json["business"]["name"] = $result_business["B_NAME"];

Passing multiple dimension array in PHP

MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}

PHP - how to use array in function?

I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function

Categories