I have a query, how do I get the result as an array?
function get_all_transaksi_proses() {
$rs = $this->db->query("SELECT a.id_transaksi,
a.nama,
a.tgl_transaksi,
(SELECT COUNT( id_transaksi ) AS jum
FROM tbl_detail_trs_menu
WHERE id_transaksi = a.id_transaksi) AS jumlah,
a.status_transaksi,
a.total,
b.status_pelanggan,
c.nama_karyawan
FROM tbl_transaksi a
LEFT JOIN tbl_pelanggan b
ON a.id_pelanggan = b.id_pelanggan
LEFT JOIN tbl_karyawan c
ON a.id_karyawan = c.id_karyawan
WHERE a.status_transaksi = 'PROSES' ");
echo json_encode(array("result" => $rs));
}
Like this:
$rs = $this->db->query(...);
$array = $rs->result_array();
https://www.codeigniter.com/user_guide/database/results.html
To get a result in array you have to do this CI 2.2.2:
return $query->result_array();
$query = $this->db->query("select....");
return $query->result(); // it will result an array
or
echo json_encode($query->result()); // this will also result array but direct to json_encode
....hope i help you!
Related
How to get count of the sql search query
$u = new user();
$sql = "SELECT a.id FROM `accounts` AS a LEFT JOIN `users` AS u ON a.id = u.id WHERE a.id IS NOT NULL ";
$gender = $this->input->post('gender');
if($gender != NULL)
{
$sql .= "AND u.gender = '".$gender."' ";
}
$u->query($sql);
How to get count of the query results in $u->query($sql); .I need to set a validation on it. If the query results count is 0 , i need to set a message. Im using PHP Codeigniter ,datamapper library.
Thank you!!!
Just using count() function like this
...
$result = $u->query($sql);
$total_data = count($result);
if($u->exists())
{
echo "Found" // Do something
}
else
{
echo "Nothing found" //Do something
}
$result = $this->db->get();
For Codeigniter use $count = $result->num_rows(); // HERE IS YOUR COUNT
For OOP PHP use $count = $result->num_rows;
How do I pull out the id in front of each JSON return object from my API?
Current:
{
"1516":{
"id":"1516",
"firstname":"Aluno",
"lastname":"Teste",
"email":"teste#gmail.com",
"dlastaccess":"28-10-2016",
"coursename":"Curso Demonstra\u00e7\u00e3o"
}
}
How do I want to leave:
[
{
"id":"1516",
"firstname":"Aluno",
"lastname":"Teste",
"email":"teste#gmail.com",
"dlastaccess":"28-10-2016",
"coursename":"Curso Demonstra\u00e7\u00e3o"
}
]
I'm trying to do this because my checklist-model does not work the way the JSON return comes, so I can not check all the checkboxes.
API:
This does the job:
$json = '{"1516":{"id":"1516","firstname":"Aluno","lastname":"Teste","email":"teste#gmail.com","dlastaccess":"28-10-2016","coursename":"Curso Demonstra\u00e7\u00e3o"}}';
$values = json_decode($json, true);
$values = array_values($values);
echo json_encode($values);
returns:
[{"id":"1516","firstname":"Aluno","lastname":"Teste","email":"teste#gmail.com","dlastaccess":"28-10-2016","coursename":"Curso Demonstra\u00e7\u00e3o"}]
I guess your $result is an array (or object) of this type:
$result[id] = array(sql retrieved);
Because sql returns you a list of results, even if the result is unique. Imagine that your query returned two results, how could you separate them?
Try:
echo json_encode($result[$cursoid])
or
echo json_encode($result->$cursoid)
$cursoid = $_GET['idcurso'];
$sql = 'SELECT
user2.id AS ID,
user2.firstname AS Firstname,
user2.lastname AS Lastname,
user2.email AS Email,
IF (user2.lastaccess = 0,"nunca",
DATE_FORMAT(FROM_UNIXTIME(user2.1astaccess),"%d-96m-W")) AS dLastAccess ,c.fullname AS Coursename
FROM mdl_user_enrolments AS ue
JOIN mdl_enrol AS e ON e.id = ue.enrolid
JOIN mdl_course AS c ON c.id = e.courseid
JOIN mdl_user AS user2 ON user2 .id = ue.userid
WHERE (SELECT timeaccess FROM mdl_user_lastaccess WHERE userid=user2.id AND courseid=c.id) IS NULL and c.id = ?';
$params = array($cursoid);
$result = $DB->get_records_sql($sql, $params);
echo json_encode(array_values($result)); // You can easily access array values without their keys by array_values(array $param) function
Use array_values, default php function
$values = $DB->get_records_sql( $sql, $params );
$result = array_values( $values );
return json_encode($result);
The code I have is the following
$sql = <<<SQL
SELECT p . * , s . *
FROM am_user p
INNER JOIN am_user_status s
USING ( user_id )
WHERE product_id =4
AND partner_logo = '1'
ORDER BY RAND( )
LIMIT 6
SQL;
$array = Array();
while ($row = mysql_fetch_array($result)) {
$array[] = $result;
}
echo $array;
However I am getting an error, I am just trying to get the results into an array. Does anyone know how I can achieve this?
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /var/sites/c/xxxxxxx/public_html/index.php on line 26
Thanks!
$sql = mysql_query("
SELECT p . * , s . *
FROM am_user p
INNER JOIN am_user_status s
USING ( user_id )
WHERE product_id =4
AND partner_logo = '1'
ORDER BY RAND( )
LIMIT 6";
$array = Array();
while ($row = mysql_fetch_array( $sql )) {
$array[] = $row;
}
echo "<pre>";
print_r( $array );
You have the sql statement, byt forgot to send it to mysql.
...
$result = mysql_query($SQL); // you forgot this
$array = Array();
while ($row = mysql_fetch_array($result)) {
$array[] = $result;
}
var_dump($array) ; // not echo $array
So I have this array data which i want to be coded somewhat like [lojas, raparacoes, valor],[nome_1, count_1, val_1],[nome_2, count_2, val_2], etc, etc...
lojas, reparacoes and valor are like headers
nome_* comes from $row['nome']
count_* comes from intval($row['COUNT( DISTINCT id_reparacao )'])
val_* comes from intval($row2['SUM(valor)'])
$data = array(array('Lojas'), array('Reparacoes'), array('Valor'));
$qry=mysql_query ('SELECT COUNT( DISTINCT id_reparacao ) , lojas.nome, lojas.id
FROM reparacoes
INNER JOIN lojas ON lojas.id = id_loja
GROUP BY lojas.id ');
while($row = mysql_fetch_array($qry))
{
$qry2=mysql_query ('SELECT SUM(valor) FROM re_servicos where id_reparacao=(select id_reparacao from reparacoes where id_loja='.$row['id'].' and estado="Fechada")');
while($row2 = mysql_fetch_array($qry2))
{
$data=[$row['nome'],intval($row['COUNT( DISTINCT id_reparacao )']), intval($row2['SUM(valor)'])];
}
}
However, with this code I'm not getting the desired output in the array, I guess the problem is the way i fill it but I don't know how to properly fill it so it gets the output I posted in the first paragraph.
PS: I don't know if it matters but for better understanding, I need this array to build a google bar chart
You can try this code.
$data = array();
$data[] = array('Lojas', 'Reparacoes', 'Valor');
$qry=mysql_query ('SELECT COUNT( DISTINCT id_reparacao ) , lojas.nome, lojas.id
FROM reparacoes
INNER JOIN lojas ON lojas.id = id_loja
GROUP BY lojas.id ');
while($row = mysql_fetch_array($qry))
{
$qry2=mysql_query ('SELECT SUM(valor) FROM re_servicos where id_reparacao=(select id_reparacao from reparacoes where id_loja='.$row['id'].' and estado="Fechada")');
while($row2 = mysql_fetch_array($qry2))
{
$data[]=array($row['nome'],intval($row['COUNT( DISTINCT id_reparacao )']), intval($row2['SUM(valor)']));
}
}
I'm trying to mesh the below mysql query results into a single json object, but not quite sure how to do it properly.
$id = $_POST['id'];
$sql = "SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = '$id'
ORDER BY contracts.end_date";
$sql2 = "SELECT types_id
FROM contracts_types
WHERE contracts_id = '$id'";
//return data
$sql_result = mysql_query($sql,$connection) or die ("Fail.");
$arr = array();
while($obj = mysql_fetch_object($sql_result)) { $arr[] = $obj; }
echo json_encode($arr); //return json
//plus the selected options
$sql_result2 = mysql_query($sql2,$connection) or die ("Fail.");
$arr2 = array();
while($obj2 = mysql_fetch_object($sql_result2)) { $arr2[] = $obj2; }
echo json_encode($arr2); //return json
Here's the current result:
[{"po_number":"test","start_date":"1261116000","end_date":"1262239200","description":"test","taa_required":"0","account_overdue":"1","jobs_id":null,"job_number":null,"companies_id":"4","companies_name":"Primacore Inc."}][{"types_id":"37"},{"types_id":"4"}]
Notice how the last section [{"types_id":"37"},{"types_id":"4"}] is placed into a separate chunk under root. I'm wanting it to be nested inside the first branch under a name like, "types".
I think my question has more to do with Php array manipulation, but I'm not the best with that.
Thank you for any guidance.
Combine the results into another structure before outputting as JSON. Use array_values to convert the type IDs into an array of type IDs. Also, fix that SQL injection vulnerability. Using PDO, and assuming the error mode is set to PDO::ERRMODE_EXCEPTION:
$id = $_POST['id'];
try {
$contractQuery = $db->prepare("SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = ?
ORDER BY contracts.end_date");
$typesQuery = $db->prepare("SELECT types_id
FROM contracts_types
WHERE contracts_id = ?");
$contractQuery->execute(array($id));
$typesQuery->execute(array($id));
$result = array();
$result['contracts'] = $contractQuery->fetchAll(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
echo json_encode($result); //return json
} catch (PDOException $exc) {
...
}
If $contractQuery returns at most one row, change the fetch lines to:
$result = $contractQuery->fetch(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
It would seem like you'd be better served by consolidating the two queries with a JOIN at the SQL level. However, assuming the two arrays have equal length:
for ($x = 0, $c = count($arr); $x < $c; $x++) {
if (isset($arr2[$x])) {
$arr[$x] += $arr2[$x];
}
}
echo json_encode($arr);
Edit: you would need to change from mysql_fetch_object to mysql_fetch_assoc for this to work properly.
Why are you using 2 distinct arrays ? I would simply add the rows of the 2nd query in $arr instead of $arr2. This way, you end up with a single array containing all rows from the 2 queries.