Codeigniter modify database query array item - php

I'm attempting to modify a date field from my database before it gets outputted to the view, but I'm not having much luck. This code doesn't seem to work, what am I doing wrong?
function get_journal_entry($id)
{
$sql = 'SELECT * FROM journal WHERE user_id = '.$this->tank_auth->get_user_id().' AND id = '.$id;
$query = $this->db->query($sql);
$query['created'] = date("c", strtotime($query['created']));
return $query->row_array();
}

$this->db->query returns a query object, not your results. You need to modify the row after calling $query->row_array.
$query = $this->db->query($sql);
$result = $query->row_array();
$result['created'] = date("c", strtotime($result['created']));
return $result;

Another version of the code, which may work:
function get_journal_entry($id)
{
$sql = 'SELECT * FROM journal WHERE user_id = ' . intval($this->tank_auth->get_user_id()) . ' AND id = ' . intval($id);
$row = $this->db->query($sql)->row_array();
$row['created'] = date("c", strtotime($row['created']));
return $row;
}

Related

How to return more mysql rows in function?

I want to make a function in PHP to return a list of mysql results. But i want to enter my own tekst also.
When i echo i get the results but i want to return the value.
function Get() {
$sql = mysqli_query($link, "SELECT * FROM blabla");
$value4 = 'certain';
while($approw = mysqli_fetch_array($sql)){
$value= 'Fun '. $approw['value1'].' '.$approw['value2'].' '.$approw['value3'].'percent '.$value4.'<br />' ;
}
return $value.' Powered by Hisenseb';
}
?>
In the while the results can change anytime
How can i do this? Can anyone tell me how? Thanks in advance.
Pass a mysqli::connect() object to the Get() function as an argument, and for example, select a array as the return value where you store the result set from the sql query and the text you want. Try it:
function Get(mysqli $connect)
{
$ret = [];
$value4 = 'certain';
if ($res = $connect->query("SELECT * FROM blabla")) {
$row = $res->fetch_all(MYSQLI_ASSOC);
$ret['mytext'] = 'Fun '. $row['value1'].' '.$row['value2'].' '.$row['value3'].'percent '.$value4.'<br />' ;
$ret['result-set'] = $row;
}
$connect->close();
return count($ret) > 0 ? $ret : false;
}
Now just call the function:
$conn = new mysqli("localhost","user","password","database");
$result = Get($conn);
$sql = $result['result-set'];
$mytext = $result['mytext'];
// You can then get the data from the sql table using the column names of your table:
$column1 = $sql['column1']; //Now in $column1 you have the value from the SQL table from column column1.

Codeigniter 4: how do I get a series of the next and previous rows using the builder class or even with a regular query

This is my current query which retrieves an item according to a parameter in the URL($qs):
I would like to get 2 or 3 of the previous and next rows of the item.
public function show_questions($qs = false)
{
$db = \Config\Database::connect();
$builder->select('*');
$builder->where('question_id ='. $qs);
$builder->join('segments_en', 'questions_en.tape = segments_en.tape');
$query = $builder->get();
return $query->getResultArray();
}
I separated table name(movie), id column name (Movie_ID) and Limit(2) to variables, because I used a sample tables (with movies to testing)
I attached the result
public function show_questions($qs = false)
{
$sql = array();
$table = "questions_en";
$joined_table = "segments_en";
$id_key = "question_id";
$limit = 2;
$db = \Config\Database::connect();
$builder = $db->table($table);
// Select previous records
$builder->select('*');
$builder->join($table, $table.'.tape = '.$joined_table.'.tape');
$builder->where($id_key.' >'. $qs);
$builder->orderBy($id_key, 'ASC');
$builder->limit($limit);
$sql[] = '('. $builder->getCompiledSelect() .')';
// Select record which is identified by ID ($qs)
$builder->select('*');
$builder->join($table, $table.'.tape = '.$joined_table.'.tape');
$builder->where($id_key, $qs);
$sql[] = '('. $builder->getCompiledSelect() .')';
// Select next records
$builder->select('*');
$builder->join($table, $table.'.tape = '.$joined_table.'.tape');
$builder->where($id_key.' <'. $qs);
$builder->orderBy($id_key, 'DESC');
$builder->limit($limit);
$sql[] = '('. $builder->getCompiledSelect() .')';
$sql_query = implode('
UNION
', $sql);
$query_string = "SELECT * FROM ($sql_query) questions ORDER BY ".$id_key." ASC";
$query = $db->query($query_string);
//var_dump($query->getResultArray());
return $query->getResultArray();
}

Use Equation Variable in Codeiginiter

Hi guys I tried to use the variable equation on Codeigniter as in the code I wrote below, Is my code writing correct? and here's my code so far I wanna using variable $amount in my controller
In Controller
$amount = $this->m_data->getTotalSales->$data['TOTAL_SALES'];
and this in Model
//GET TOTAL REVENUE
function getTotalSales(){
$this->db->select("(SELECT SUM(grand_total) FROM sales_order WHERE member = ".$this->session->userdata('ID').") - (SELECT SUM(amount) FROM payment WHERE member_id = ".$this->session->userdata('ID').") AS total_sales");
$query = $this->db->get();
if ($query->num_rows() >0){
foreach ($query->result() as $data) {
$hasilSemua[] = $data;
}
return $hasilSemua;
}
}
$amount = $this->m_data->getTotalSales();
function getTotalSales(){
$result1 = $this->db->select_sum("grand_total")
->from('sales_order')
->where("member = $this->session->userdata('ID')");
->get();
$result2 = $this->db->select_sum("amount")
->from('payment')
->where("member_id = $this->session->userdata('ID')")
->get();
return $result1->row()-$result2->row();
}
}
I believe this is what you are after. Note that I pass the UserID in as the second parameter to the WHERE function. This is in case there is any chance of the user having inputted it (always safter to do this anyway).
//GET TOTAL REVENUE
function getTotalSales(){
$db = $this->db;
$db->select('SUM(grand_total)');
$db->where('member',$this->session->userdata('ID'));
$q1 = $db->get_compiled_select('sales_order');
$db->select('SUM(amount)');
$db->where('member_id',$this->session->userdata('ID'));
$q2 = $db->get_compiled_select('payment');
$query = $db->query("SELECT ($q1) - ($q2) as total_sales");
$data = $query->row_array();
return $data['total_sales'];
}
You can then call $amount = $this->m_data->getTotalSales; to get your result.

Return multiple rows of an array from a mysqli query

I have this in my functions.php file
function getUserOrders($userId){
global $conn;
$query = "SELECT * ";
$query .= "FROM orders ";
$query .= "WHERE userid=" . $userId . " ";
$odrset = mysqli_query($conn, $query);
while ($odr = mysqli_fetch_assoc($odrset)){
return $odr;
}
}
What I neeed to do in my orders.php file is display specific fields and their values from the returned $odr array as this snippet suggests
$userId = sql_prep($_SESSION['userid']) ;
getUserOrders($userId);
echo $odr['title'].$odr['orderid'].'<br>'
I am only able to do it in the functions.php file...
function getUserOrders($userId){
global $conn;
$query = "SELECT * ";
$query .= "FROM orders ";
$query .= "WHERE userid=" . $userId . " ";
$odrset = mysqli_query($conn, $query);
confirm_query($odrset);
while ($odr = mysqli_fetch_assoc($odrset)){
echo $odr['title'].$odr['orderid'].'<br>';
}
}
..and calling it in my orders.php file like so:
$userId = sql_prep($_SESSION['userid']) ;
getUserOrders();
which is not good since i need to recycle the function somewhere else and display different fields and their values. So I need to have $odr returned as an array in my order.php
Store it as an array and then return the array.
function getUserOrders($userId){
global $conn;
$query =
"SELECT *
FROM orders
WHERE userid= ?";
$odrset = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($odrset, 'i', $userId);
mysqli_stmt_execute($odrset);
while ($odr = mysqli_fetch_assoc($odrset)){
$return[] = $odr;
}
return $return;
}
I've updated your mysqli connection to use a parameterized query with prepared statement. You can read more about these here, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php. This is the preferred approach than escaping.
Later usage...
$orders = getUserOrders($_SESSION['userid']);
foreach($orders as $order) {
echo $order['title'] . $order['orderid'];
}
You may not need the sql_prep function with this approach, I'm not sure what that did. Your questions code didn't pass the userid to the function so I don't think that was your exact usage.
mysqli_fetch_assoc only returns one record at a time so you need to store the results inside an array and return the array from the function:
// functions.php
function getUserOrders($userId){
global $conn;
$query = "SELECT * ";
$query .= "FROM orders ";
$query .= "WHERE userid=" . $userId . " ";
$odrset = mysqli_query($conn, $query);
$results = array();
while ($odr = mysqli_fetch_assoc($odrset)){
$results[] = $odr;
}
return $results;
}
// in your orders file
$userid = sql_prep($_SESSION['userid']);
$orders = getUserOrders($userid);
foreach ($order as $orders) {
echo $order['title']. $order['orderid'] . '<br>';
}

how to return value of selected id in database php

I insert in the database a csv file. how will i return the id and use it to insert in another table. it always displays array to string conversion errror. is there something wrong with "return"
here is my controller
public function uploadThree(){
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false)
{
$appname = $fileop[0];
$servname = $fileop[1];
$ciname = $fileop[2];
$servid = $this->some_model->insertBulkServ($servname); //i tried to get the value here then insert below
$appid = $this->some_model->insertBulkSingleApp($appname);//i tried to get the value here then insert below
$this->some_model->insertBulkCI($ciname);
$this->some_model->ASMAP($appid,$servid);
}
if($success == TRUE)
redirect(base_url().'some_controller/uploadPage');
}
MODEL
public function insertBulkServ($service) {
/* Inserts csv file for a service */
$service = $this->db->escape_str($service);
$queryStr = "Select service from appwarehouse.service where service = '$service' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
$queryStr = "SELECT id FROM appwarehouse.service WHERE service='$service' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
//in here how do i get the ID how do i return it
}else{
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$service');";
$query = $this->db->query($queryStr);
$queryStr = "SELECT id FROM appwarehouse.service WHERE service='$service' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
}
public function insertBulkSingleApp($app_name) {
/* Inserts csv file for an application */
$app_name = $this->db->escape_str($app_name);
$queryStr = "Select * from appwarehouse.application_table where app_name = '$app_name' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
else{
$queryStr = "INSERT INTO appwarehouse.application_table(app_name)
VALUES ('$app_name');";
$query = $this->db->query($queryStr);
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
}
public function ASMAP($appid,$servid) {
$appid = $this->db->escape_str($appid);
$servid = $this->db->escape_str($servid);
$queryStr = "Select * from appwarehouse.app_service where app_id = '$appid' AND serv_id = '$servid' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
return true;
}
else{
$queryStr = "INSERT INTO appwarehouse.app_service(app_id,serv_id)
VALUES ('$appid','$servid');";
$query = $this->db->query($queryStr);
return true;
}
}
What you probably want is:
$this->db->insert_id()
The insert ID number when performing database inserts.
More Info: http://ellislab.com/codeigniter/user-guide/database/helpers.html
You need to do it it is very simple
After the query insert
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$service');";
Instead of select use this
return $this->db->insert_id();
Or if you really need to return the object
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
Return id instead of object
return $query->row()->id;
One more thing to note. insert_id is the last inserted id so you dont have to run select query to get id.
Also use row() to select single record. result() selects multiple records so you will get an array. see here.

Categories