I have this php function in codeigniter where it fetches the data from my database:
function fetch_data()
{
$data = $this->projectionchart_model->make_query();
$array = array();
foreach($data as $row)
{
$array[] = $row;
}
$output = array(
'current' => intval($_POST["current"]),
'rowCount' => 10,
'total' => intval($this->projectionchart_model->count_all_data()),
'rows' => $array
);
echo json_encode($output);
}
I want to use the number_format function to some of columns and right now it's building everything in an array. How could I remove the array and list the data individually as variables so I can apply a function to some of them and then output them?
Thank you
Edit: explaining in more detail
This function fetch_data() calls the make_query() function stored in the projectionchart_model file which contains the following:
function make_query()
{
if(isset($_POST["rowCount"]))
{
$this->records_per_page = $_POST["rowCount"];
}
else
{
$this->records_per_page = 10;
}
if(isset($_POST["current"]))
{
$this->current_page_number = $_POST["current"];
}
$this->start_from = ($this->current_page_number - 1) * $this->records_per_page;
$this->db->select("*");
$this->db->from("projection_chart");
if(!empty($_POST["searchPhrase"]))
{
$this->db->like('ae', $_POST["searchPhrase"]);
$this->db->or_like('client', $_POST["searchPhrase"]);
$this->db->or_like('product', $_POST["searchPhrase"]);
$this->db->or_like('week_of', $_POST["searchPhrase"]);
$this->db->or_like('month', $_POST["searchPhrase"]);
$this->db->or_like('type', $_POST["searchPhrase"]);
}
if(isset($_POST["sort"]) && is_array($_POST["sort"]))
{
foreach($_POST["sort"] as $key => $value)
{
$this->db->order_by($key, $value);
}
}
else
{
$this->db->order_by('id', 'DESC');
}
if($this->records_per_page != -1)
{
$this->db->limit($this->records_per_page, $this->start_from);
}
$query = $this->db->get();
return $query->result_array();
}
So the output currently is this:
I want to format the Planned Spend, Cleared and Total Commission with the number_format php function but right now it's all in an array.
How could I accomplish this?
I have an update query problem in CodeIgniter. I am trying to solve that problem but I can't. I have one array $arrpartnerId=([0=>1,[1]=>4,[3]=>5 like..) and my other array is $promotionData['promotion_id']. The inserting into checkbox value is correct, but the updating checkbox value is not working.
My model function is:
public function update_promotion($promotionData, $partnerData) {
// print_r( $promotionData['promotion_id']);
$arrPartnerId = $partnerData['partner_id'];
print_r($partnerData['partner_id']);
if (is_array($arrPartnerId) > 0) {
foreach ($arrPartnerId as $partnerId) {
$this->db->set('promotion_id', $promotionData['promotion_id']);
$this->db->where('partner_id', $partnerId);
$this->db->update('partner_promotion_relation');
}
}
}
If your array is like this,
$arrPartnerId = array(
0 => 1,
1 => 4,
2 => 5
);
And
$promotionData['promotion_id'] = 123; //assumption
Then try this,
if(sizeof($arrPartnerId) > 0 )
{
foreach( $arrPartnerId as $partnerId)
{
$this->db->set('partner_id', $partnerId );
$this->db->where('promotion_id', $promotionData['promotion_id'] );
$this->db->update('partner_promotion_relation');
}
}
It will resolve the problem.
I have this function : it's work correctly,
function ms_get_did_detail($id) {
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2)) {
while($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC)) {
return $row2;
}
return 0;
}
return 0;
}
I want insert every element (every Dest & Priority) into MYSQL
if($info=ms_get_did_detail($value)) {
print_r($info);
$destination = $info['Dest'];
$priority = $info['Priority'];
my_did_destination ($priority , $dest , $active , $did_voip , $cc_id);
}
It returns array like this :
[0]=> Array (
[Dest] => 100
[Priority] => 1
)
[1]=> Array (
[Dest] => 200
[Priority] => 3
)
[2] => (
)
also , I have this function to insert value in database :
function my_did_destination($priority="",$destination="") {
global $link_voip;
$sql="INSERT INTO cc_did_destination (destination,priority)
VALUES ('$destination','$priority')";
$retval = mysql_query( $sql , $link_voip);
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
}
but It's insert empty value within
You are inserting all rows with an ID of 0, so, if a row with id=0 already exists, it will fail and will not be inserted.
Maybe the easiest solution would be to make yout ID column autoincrement with an SQL statement like:
ALTER TABLE cc_did_destination
MODIFY COLUMN id INT auto_increment;
And then change your INSERT statement for:
$sql="INSERT INTO cc_did_destination (destination,priority)
VALUES ('$destination','$priority')";
Your $info is array of rows, it has numeric keys, not 'Dest'.
You should add index, like $dest = $info[0]['Dest'].
if($info=ms_get_did_detail($value))
{
print_r($info);
$dest = $info[0]['Dest'];
$priority = $info[0]['Priority'];
my_did_destination ($priority , $dest , $active , $did_voip , $cc_id);
}
Or you can iterate through $info with a loop:
if($info=ms_get_did_detail($value))
{
foreach($info as $row) {
$dest = $row['Dest'];
$priority = $row['Priority'];
my_did_destination ($priority , $dest);
}
}
also, remove id from your insert statement
your array is:
[0]=> Array (
[Dest] => 100
[Priority] => 1
)
[1]=> Array (
[Dest] => 200
[Priority] => 3
)
[2] => (
)
so it is a multidimensional array. if you need to insert all those entries, you shouldn't run multiple queries for the same thing. just use mysql batch insert syntax. (e.g. INSERT INTO tbl (col1,col2,col3) VALUES(a,b,c),(d,e,f),(g,h,i))
build the query string for insert.
foreach($a as $i => $v)
{
$b[] = '("'.$v['Dest'].'","'.$v['Priority'].'")';
}
$c = implode(',', $b);
$sql = "INSERT INTO cc_did_destination (destination,priority)
VALUES ".$c;
then run the query
N.B.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
There are a couple of issues here.
Firstly your first function returns an array of arrays. Ie, it returns an array with subscript 0 for the first row (it only ever returns one rows details), which is an array containing that rows details.
You assign this to the $info variable, so it contains:-
[0]=> Array (
[Dest] => 100
[Priority] => 1
)
You then assign $info['Dest'] to $destination and $info['Priority'] to $priority. However neither of these exist. You would need $info[0]['Dest'] and $info[0]['Priority'].
2nd issue is that you are trying to assign a specific value to the auto increment id field. Just leave it out of the insert, or give it a value of null.
Quick rewrite and I would suggest you need something like this:-
<?php
if($info=ms_get_did_detail($value))
{
print_r($info);
foreach($info AS $info_row)
{
$destination = $info_row['Dest'];
$priority = $info_row['Priority'];
my_did_destination ($priority , $dest , $active , $did_voip , $cc_id);
}
}
function ms_get_did_detail($id)
{
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2))
{
if ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
while ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
}
return $row2;
}
else
{
return 0;
}
}
return 0;
}
function my_did_destination($priority="",$destination="")
{
global $link_voip;
$priority = mysql_real_escape_string($priority);
$destination = mysql_real_escape_string($destination);
$sql="INSERT INTO cc_did_destination (id,destination,priority) VALUES (NULL,'$destination','$priority')";
$retval = mysql_query( $sql , $link_voip);
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
}
EDIT
If you want to avoid multiple inserts unnecessarily then it might be easier to use an object. This way you can do the inserts easily when there are enough batched up (I normally do 255 at a time).
Something like this, although you probably should use mysqli_*
<?php
if($info=ms_get_did_detail($value))
{
print_r($info);
$insert_object = new insert_details($link_voip);
foreach($info AS $info_row)
{
$insert_object->set_row($info_row['Priority'], $info_row['Dest']);
}
unset($insert_object);
}
function ms_get_did_detail($id)
{
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2))
{
if ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
while ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
}
return $row2;
}
else
{
return 0;
}
}
return 0;
}
class insert_details()
{
private $db;
private $insert_row = array();
public function __CONSTRUCT($db)
{
$this->db = $db;
}
public function __DESTRUCT()
{
$this->do_insert();
}
public function set_row($priority="",$destination="")
{
$priority = mysql_real_escape_string($priority, $this->db);
$destination = mysql_real_escape_string($destination, $this->db);
$this->insert_row[] = "(NULL,'$destination','$priority')";
if (count($this->insert_row) > 255)
{
$this->do_insert();
}
}
private function do_insert()
{
$sql="INSERT INTO cc_did_destination (id,destination,priority) VALUES ".implode(',', $this->insert_row);
$retval = mysql_query($sql, $this->db);
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
$this->insert_row = array();
}
}
Quick rough mysqli_* equivalent, assuming that $link_voip is a mysqli connection. Note that prepared statements with bound parameters are an option (and it makes it harder to forget to escape variables), but it can become a bit messy when you are doing multiple inserts like this.
<?php
if($info=ms_get_did_detail($value))
{
print_r($info);
$insert_object = new insert_details($link_voip);
foreach($info AS $info_row)
{
$insert_object->set_row($info_row['Priority'], $info_row['Dest']);
}
unset($insert_object);
}
function ms_get_did_detail($id)
{
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2))
{
if ($row2[]=mssql_fetch_array($res2, MSSQL_ASSOC))
{
while ($row2[]=mssql_fetch_array($res2, MSSQL_ASSOC))
{
}
return $row2;
}
else
{
return 0;
}
}
return 0;
}
class insert_details()
{
private $db;
private $insert_row = array();
public function __CONSTRUCT($db)
{
$this->db = $db;
}
public function __DESTRUCT()
{
$this->do_insert();
}
public function set_row($priority="",$destination="")
{
$priority = mysqli_real_escape_string($this->db, $priority);
$destination = mysqli_real_escape_string($this->db, $destination);
$this->insert_row[] = "(NULL,'$destination','$priority')";
if (count($this->insert_row) > 255)
{
$this->do_insert();
}
}
private function do_insert()
{
$sql="INSERT INTO cc_did_destination (id,destination,priority) VALUES ".implode(',', $this->insert_row);
$retval = mysqli_query($this->db, $sql);
if(! $retval )
{
die('Could not enter data: ' . mysqli_sqlstate($this->db));
}
$this->insert_row = array();
}
}
I'm trying to get the data from array in my controller php on Cakephp.
I have this function:
public function updateUserStatus() {
if(isset($this->params['url']["pcs"])) {
$uus = array( "pcs" =>$this->params['url']["pcs"] );
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
And I want to get the data from status_id who have this response:
Array (
[0] => Array
(
[status_id] => 2
)
[1] => Array
(
[rem_time] => 66
)
)
How can I do it?
My question is how can i get the data for status_id ?
public function updateUserStatus() {
if (isset($this->params['url']["pcs"])) {
$uus = array("pcs" =>$this->params['url']["pcs"]);
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$currentStatus = 0;
if (is_array($trans) && isset($trans['status_id'])) {
$currentStatus = $trans['status_id'];
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
public function updateUserStatus($uus){
if(isset($uus["pcs"])) {
$sql = "SELECT status_id as status_id , rem_time as rem_time FROM phones WHERE pcs = '".$uus["pcs"]."' LIMIT 1";
$query = $this->query($sql);
return $query[0]['phones'];
} else {
return "failed";
}
}
Notice, we are returning $query[0]['phones'].
Let me know if it works.
The code could also use some refactoring.
For example, why is the function called updateUserStatus if it is only returning the result of a query? It should also always return an array, for consistency.
i am working on php i have dynamic array i need to get the array result store in some variable i encounter the error :array to string conversion
coding
<?php
require_once('ag.php');
class H
{
var $Voltage;
var $Number;
var $Duration;
function H($Voltage=0,$Number=0,$Duration=0)
{
$this->Voltage = $Voltage;
$this->Number = $Number;
$this->Duration = $Duration;
}}
//This will be the crossover function. Is just the average of all properties.
function avg($a,$b) {
return round(($a*2+$b*2)/2);
}
//This will be the mutation function. Just increments the property.
function inc($x)
{
return $x+1*2;
}
//This will be the fitness function. Is just the sum of all properties.
function debug($x)
{
echo "<pre style='border: 1px solid black'>";
print_r($x);
echo '</pre>';
}
//This will be the fitness function. Is just the sum of all properties.
function total($obj)
{
return $obj->Voltage*(-2) + $obj->Number*2 + $obj->Duration*1;
}
$asma=array();
for($i=0;$i<$row_count;$i++)
{
$adam = new H($fa1[$i],$fb1[$i],$fcc1[$i]);
$eve = new H($fe1[$i],$ff1[$i],$fg1[$i]);
$eve1 = new H($fi1[$i],$fj1[$i],$fk1[$i]);
$ga = new GA();
echo "Input";
$ga->population = array($adam,$eve,$eve1);
debug($ga->population);
$ga->fitness_function = 'total'; //Uses the 'total' function as fitness function
$ga->num_couples = 5; //4 couples per generation (when possible)
$ga->death_rate = 0; //No kills per generation
$ga->generations = 10; //Executes 100 generations
$ga->crossover_functions = 'avg'; //Uses the 'avg' function as crossover function
$ga->mutation_function = 'inc'; //Uses the 'inc' function as mutation function
$ga->mutation_rate = 20; //10% mutation rate
$ga->evolve(); //Run
echo "BEST SELECTED POPULATION";
debug(GA::select($ga->population,'total',3)); //The best
$array=array((GA::select($ga->population,'total',3))); //The best }
?>
<?php
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
?
>
i apply implode function but its not working
it display the error of : Array to string conversion in C:\wamp\www\EMS3\ge.php on line 146 at line $r=implode($rt,",");
<script>
if ( ($textboxB.val)==31.41)
{
</script>
<?php echo "as,dll;g;h;'islamabad"; ?>
<script>} </script>
You are running your java script code in PHP, I havent implemented your code just checked and found this bug.You can get the value by submitting the form also
---------------------------- Answer For your Second updated question------------------------
<?php
$array = array(
"name" => "John",
"surname" => "Doe",
"email" => "j.doe#intelligence.gov"
);
$comma_separated = implode(",", $array); // You can implode them with any character like i did with ,
echo $comma_separated; // lastname,email,phone
?>