This is my array:
$data = array(
'user_id' => $profile_data['user_id'],
'sender_id' => $session_user_id,
'sender_first_name' => $user_data['first_name'],
'photo_url' => 'null',
'time' => time(),
'status' => $_POST['status']
);
This is my function:
function post($data) {
array_walk($data, 'array_sanitize');
$fields = '`' . implode('`, `', array_keys($data)) . '`';
$data = '\'' . implode('\', \'', $data) . '\'';
mysql_query("INSERT INTO status ($fields) VALUES ($data) ");
if ($data['sender_id'] == 1) {
//code
}
}
How to check if the value of 'sender_id' is 1, for example?
Don't overwrite a variable if you want to be able to check it, use different variables:
$data_str = '\'' . implode('\', \'', $data) . '\'';
mysql_query("INSERT INTO status ($fields) VALUES ($data_str) ");
if ($data['sender_id'] == 1) {
// code
}
You can just say:
if ( $data['sender_id'] == 1 )
{
// do stuff
}
but in general, if you need to look around an array, this is how you do it
foreach ($data as $key => $value)
{
if ( $key == 'sender_id' && $value == 1 )
{
// do stuff
}
}
Related
I am trying to insert a key value pair at the end of an array of values retrieved from a database query. I tried array_splice but that wasn't doing exactly what I wanted, so I'm trying array_push but it's not adding it to the array.
Here is my code:
public function listFriendsStatus()
{
// get the friend statuses of the logged in user
$connection = $this->sql->getAdapter()->getDriver()->getConnection();
$query = $connection->execute("SELECT status.id, status, time_status, members.username FROM status
INNER JOIN friends ON friends.friend_id = status.id
INNER JOIN members ON members.id = status.id
WHERE friends.user_id = " . $this->getUserId()['id']);
if ($query->count() > 0) {
$status_holder = array();
foreach ($query as $key => $value) {
$status_holder[$key] = $value;
$status_dir = '/images/profile/' . $status_holder[$key]['username'] . '/status/' . $status_holder[$key]['time_status'] . '/';
$real_dir = getcwd() . '/public/' . $status_dir;
if (is_dir($real_dir)) {
$images = array_diff(scandir($real_dir, 1), array('.', '..'));
array_push($status_holder, array('images' => $images));
} else {
array_push($status_holder, array('images' => ''));
}
}
return $status_holder;
} else {
throw new FeedException("No friend statuses were found.");
}
}
For a better explanation, here is a var_export of my array
array ( 0 => array ( 'id' => '2', 'status' => 'this is jimmy, test', 'time_status' => '0', 'username' => 'jimmy', ), 1 => array ( 'id' => '3', 'status' => 'this is jimmy 2, test', 'time_status' => '0', 'username' => 'timmy', ), 2 => array ( 'images' => '', ), )
What I am trying to do is insert after each ["username"] key and value, the images key and value from the images array.
Any help would be appreciated.
Thanks!
(I can try and make the question clearer if need be)
update
$status_holder[$key]['images'] = $images;
did what I need.
If your foreach is retrieving a row at a time, then add the image into this data and then build your other array...
foreach ($query as $key => $value) {
$status_dir = '/images/profile/' . $value['username'] . '/status/' . $value['time_status'] . '/';
$real_dir = getcwd() . '/public/' . $status_dir;
if (is_dir($real_dir)) {
$images = array_diff(scandir($real_dir, 1), array('.', '..'));
$value['images'] = $images;
} else {
$value['images'] = '';
}
$status_holder[$key] = $value;
}
I want to create a .INI file based on the values I get from database.
This are the values in my database for :
Now in the field parameter filed is the value i want to write in file each in new line.
I fetch the values like this:
$this->data['params'] = $this->parameter_m->get();
So I get all the values from the table.
I want to write values in file like this:
[INIDetails]
SipUserName=
Password=
Domain=
Proxy=
Port=
SipAuthName=
DisplayName=
ServerMode=
UCServer=
UCUserName=
UCPassword=
[DialPlan]
DP_Exception=
DP_Rule1=
DP_Rule2=
[Advanced]
OperationMode=
MutePkey=
Codec=
PTime=
AudioMode=
SoftwareAEC=
EchoTailLength=
PlaybackBuffer=
CaptureBuffer=
JBPrefetchDelay=
JBMaxDelay=
SipToS=
RTPToS=
LogLevel=
I have WRITE Function that writes into file
function write($file = NULL, $file_content = array(), $sections = TRUE) {
$this->file_content = (!empty($file_content)) ? $file_content : $this->file_content;
$this->file = ($file) ? $file : $this->file;
$this->sections = $sections;
$content = NULL;
if ($this->sections) {
foreach ($this->file_content as $section => $file_content) {
$content .= '[' . $section . ']' . PHP_EOL;
foreach ($file_content as $key => $val) {
if (is_array($val)) {
foreach ($val as $v) {
$content .= $key . '[]=' . (is_numeric($v) ? $v : $v ) . PHP_EOL;
}
} elseif (empty($val)) {
$content .= $key . '=' . PHP_EOL;
} else {
$content .= $key . '=' . (is_numeric($val) ? $val : $val ) . PHP_EOL;
}
}
$content .= PHP_EOL;
}
} else {
foreach ($this->file_content as $key => $val) {
if (is_array($val)) {
foreach ($val as $v) {
$content .= $key . '[] = ' . (is_numeric($v) ? $v : '"' . $v . '"') . PHP_EOL;
}
} elseif (empty($val)) {
$content .= $key . ' = ' . PHP_EOL;
} else {
$content .= $key . ' = ' . (is_numeric($val) ? $val : '"' . $val . '"') . PHP_EOL;
}
}
}
return (($handle = fopen($this->file, 'w+')) && fwrite($handle, trim($content)) && fclose($handle)) ? TRUE : FALSE;
}
And i use that function like this :
$path = "./uploads/";
$filename = "default.ini";
$this->load->helper('file');
$file = $path.$filename;
$this->load->library('ini');
$ini = new INI($file);
$ini->write($file, $this->data['params']);
So i how to write the array of values i get from database into file ?
As you can see there is a filed called Parameter_Type i want to set it as section in INI file.
I'm guessing that your parameter_m is your model which have get() function where it returns array values from your table. What I think, the problem is that your model return incorrect structure of your array. Your array should have structure like:
array(
"parameter_type" => array(
"parameter" => value
)
)
in your model's get function, there should be something like:
class parameter_m extends CI_Model {
public function get()
{
$query = $this->db->get('your_parameter_table');
$assoc_arr = array();
foreach ($query->result() as $row)
{
$assoc_arr[$row->parameter_type][$row->parameter] = '';
}
return $assoc_arr;
}
}
Using the get() it should output:
array(
"INIDetails" => array(
"SipUserName" => '',
"Password" => '',
"Domain" => '',
"Proxy" => '',
"Port" => '',
"SipAuthName" => '',
"DisplayName" => '',
"ServerMode" => '',
"UCServer" => '',
"UCUserName" => '',
"UCPassword" => ''
),
"DialPlan" => array(
"DP_Exception" => '',
"DP_Rule1" => '',
"DP_Rule2" => ''
),
"Advanced" => array(
"OperationMode" => '',
"MutePkey" => '',
"Codec" => '',
"PTime" => '',
"AudioMode" => '',
"SoftwareAEC" => '',
"EchoTailLength" => '',
"PlaybackBuffer" => '',
"CaptureBuffer" => '',
"JBPrefetchDelay" => '',
"JBMaxDelay" => '',
"SipToS" => '',
"RTPToS" => '',
"LogLevel" => ''
)
);
Here is my code. It is insert only last element value. I want to insert all value in one field with different id and all data insert in different different row.
public function update($user_slider, $user_welcomebox, $user_servicebox, $user_postbox, $user_testimonials, $user_welcomemessage, $user_welcomededcription, $user_welcomelink, $user_welcomelinktitle, $user_servicetitle, $user_totalservicedisplay, $user_ourservice, $user_blogtitle, $user_totalblogdisplay,$user_ourblog, $user_newstitle, $user_totalnewsdisplay, $user_ournews, $user_totaltestimonialdisplay, $user_ourtestimonial) {
$db = connectionstart();
$currentdatetime = date("Y-m-d H:i:s", time());
$currentgmtdatetime = gmdate("Y-m-d H:i:s", time() - (5 * 60 * 60));
$sql = "select * from user_options ";
$result = mysql_evaluate($db, $sql, 0);
$columns = array(
"name" => 'slider'
, "value" => $user_slider
,"name" => 'welcomebox'
, "value" => $user_welcomebox
,"name" => 'servicebox'
, "value" => $user_servicebox
,"name" => 'postbox'
, "value" => $user_postbox
,"name" => 'testimonials'
, "value" => $user_testimonials
,"name" => 'welcomemessage'
, "value" => $user_welcomemessage
,"name" => 'welcomededcription'
, "value" => $user_welcomededcription
,"name" => 'welcomelink'
, "value" => $user_welcomelink
,"name" => 'welcomelinktitle'
, "value" => $user_welcomelinktitle
,"name" => 'servicetitle'
, "value" => $user_servicetitle
,"name" => 'totalservicedisplay'
, "value" => $user_totalservicedisplay
,"name" => 'ourservice'
, "value" => $user_ourservice
,"name" => 'blogtitle'
, "value" => $user_blogtitle
,"name" => 'totalblogdisplay'
, "value" => $user_totalblogdisplay
,"name" => 'ourblog'
, "value" => $user_ourblog
,"name" => 'newstitle'
, "value" => $user_newstitle
,"name" => 'totalnewsdisplay'
, "value" => $user_totalnewsdisplay
,"name" => 'ournews'
, "value" => $user_ournews
,"name" => 'totaltestimonialdisplay'
, "value" => $user_totaltestimonialdisplay
,"name" => 'ourtestimonial'
, "value" => $user_ourtestimonial
, "entrydate" => $currentdatetime
);
if ($result != 0) {
$result = mysql_update($db, "user_options", $columns, "");
if ($result == true) {
$result = 'SUCCESS';
}
} else {
$result = mysql_insert($db, "user_options", $columns, "");
if ($result == true) {
$result = 'SUCCESS';
}
}
connectionclose($db);
return $result;
}
this code insert only last value like this
id name value
1 testimonials 5
i want to insert data like this
id name value
1 slider 0
2 welcome box 1
3 welcome message hi
Function for update
if (!function_exists('mysql_update')) {
function mysql_update($db, $table, $columns, $where = "") {
$sql = "UPDATE `" . $table . "` SET";
$arry = array();
foreach ($columns as $field => $value) {
array_push($arry, " `" . $field . "`='" . $value . "' ");
}
// implode keys of $array...
$sql .= implode(",", $arry);
if (isset($where) && $where != "") {
$sql .= " " . $where;
}
$result = mysql_query($sql, $db) or die(mysql_error());
return $result;
}
}
function for insert
if (!function_exists('mysql_insert_multiple')) {
function mysql_insert_multiple($db, $table, $columns) {
$sql = "INSERT INTO `" . $table . "` ";
// implode keys of $array...
$sql .= " (`" . implode("`, `", array_keys($columns[0])) . "`)";
// implode values of $array...
$sql .= " VALUES ";
$tempstr = array();
foreach ($columns as $row) {
$tempstr[] = " ('" . implode("', '", $row) . "') ";
}
$sql.=implode(',', $tempstr);
$sql.=";";
$result = mysql_query($sql, $db) or die(mysql_error());
return $result;
}
}
You can user your query with in a loop to insert the multiple recoded in a field at a time.
Change your sql for insert into this :
function mysql_insert_multiple($db, $table, $columns) {
$sql = "INSERT INTO `" . $table . "` ";
// implode keys of $array...
$sql .= " (`" . implode("`, `", array_keys($columns[0])) . "`)";
// implode values of $array...
$sql .= " VALUES ";
$tempstr = array();
foreach ($columns as $row) {
$tempstr[] = " ('" . implode("', '", array_values($row)) . "') ";
$sql.=implode(',', $tempstr);
$sql.=";";
$result = mysql_query($sql, $db) or die(mysql_error());
}
return $result;
}
This will work if your $column array is in the format:
$columns = array(
0 => array("name" => 'slider'
"value" => $user_slider.
1 =>
.
.
.
So I think you need to change your $column array as well.
Question:
I have an array of post values that looks like:
$_POST['children'] = array(
[0]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
),
[1]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
),
[2]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
)
);
// and so on
I have a script set up in my my view functions that checks for old input, and repopulates the values in the case that the form does not validate. I need to find a way to return the above array as a series of key/value pairs i.e.
'children[0][fname]' = 'name'
'children[0][mname]' = 'mname'
'children[0][lname]' = 'lname'
// ... and so on for all fields
Ideally, I would like this to work with an array of any depth, which makes me think I need some sort of recursive function to format the keys. I am having a terrible time getting my head around how to do this.
What I have tried
I have been working with the following function:
function flatten($post_data, $prefix = '') {
$result = array();
foreach($post_data as $key => $value) {
if(is_array($value)) {
if($prefix == ''){
$result = $result + flatten($value, $prefix. $key );
}else{
$result = $result + flatten($value, $prefix. '[' . $key . ']');
}
}
else {
$result[$prefix . $key .''] = $value;
}
}
return $result;
}
This gets me somewhat close, but isn't quite right. It returns the following when I feed it my $_POST array
[children[1]fname] => test
[children[1]mname] => test
[children[1]lname] => test
[children[1]dob] =>
// Expecting: children[1][fname] => test
// ...
Or is there potentially an easier way to accomplish this?
What ended up working for me:
function flatten($post_data, $prefix = '') {
$result = array();
foreach($post_data as $key => $value) {
if(is_array($value)) {
if($prefix == ''){
$result = $result + flatten($value, $prefix. $key );
}else{
$result = $result + flatten($value, $prefix. '[' . $key . ']');
}
}
else {
if( $prefix == ''){
$result[$prefix . $key.''] = $value;
}else{
$result[$prefix . '['.$key.']'.''] = $value;
}
}
}
return $result;
}
it wasn't accounting for the return value of the last call of the recursive function being a scalar value. The addition of these this if/else statement seems to have resolved it.
if( $prefix == ''){
$result[$prefix . $key.''] = $value;
}else{
$result[$prefix . '['.$key.']'.''] = $value;
}
I have an array like this
$test = array(
'Subscription' => '1',
'Streaming' => '1',
'Download' => '0'
)
so during updating to mariaDB
$query = 'UPDATE table_1 set category_dynamic = COLUMN_CREATE(' . $test . ') where id = 1';
$this->Model->query($query);
I want to save the array this way ('Subscription',1,'Streaming',1,'Download',0)
any suggestion ?
You can try this :
<?php
$test = array(
'Subscription' => '1',
'Streaming' => '1',
'Download' => '0'
);
$data = '';
foreach($test as $key=>$value)
{
$data .= '"'.$key.'"'.', '.$value.', ';
}
$data = rtrim($data,', ');
$query = 'UPDATE table_1 set category_dynamic = COLUMN_CREATE(' . $data . ') where id = 1';
Hope it will solve the problem.
You could use a combination of array_map and implode for that.
$test = array(
'Subscription' => '1',
'Streaming' => '1',
'Download' => '0'
);
$list = implode(',', array_map(function ($v, $k) { return "'".$k."'" . ',' . $v; }, $test, array_keys($test)));
$query = 'UPDATE table_1 set category_dynamic = COLUMN_CREATE(' . $list . ') where id = 1';
$this->Model->query($query);