saving php array to mariadb dynamic colum - php

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);

Related

Inserting a key value pair after a certain key value in PHP

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;
}

upload image files can not be displayed

why images can not be performed when added
if(isset($_POST['tambah'])){
$data1 = array(
'id' => $_POST['id'],
'nama' => $_POST['nama'],
'jk' => $_POST['jk'],
'tempat' => $_POST['tempat'],
'tanggal' => date('Y-m-d',strtotime("$_POST[tanggal]")),
'pekerjaan' => $_POST['pekerjaan'],
'alamat' => $_POST['alamat'],
'foto' => move_uploaded_file($FILES['photo']['temp_name'], '..asset/img/anggota/'.str_replace(' ', '-', $_POST['id'].'.jpg'))
);
use function :
function tambahAnggota($data1){
$kunci = implode(", ",array_keys($data1));
$i = 0;
foreach ($data1 as $key => $value) {
if (!is_int($value)){
$arrayValue[$i] = "'".$value."'";
}else{
$arrayValue[$i] = $value;
}
$i++;
}
$nilai = implode(", ", $arrayValue);
print_r($nilai);
die();
$s = "insert into anggota ($kunci)";
$s .= " VALUES ";
$s .= "($nilai)";
$sql = $this->db->prepare($s); /*or die ($this->db->connect_errno);*/
$sql->execute();
}
will be added all the data except the image data file to be uploaded
will look like this :
'DA123', 'David', 'laki', 'Los Angeles', '1987-03-12', 'Web Developer', 'foof st.', ''
You have an error in your path : you write '..asset/img/anggota/' which is not correct.
Try with ../asset/img/anggota/ (notice the / after ..).
Just replace :
'foto' => move_uploaded_file($FILES['photo']['temp_name'], '..asset/img/anggota/'.str_replace(' ', '-', $_POST['id'].'.jpg'))
With :
'foto' => move_uploaded_file($FILES['photo']['temp_name'], '../asset/img/anggota/'.str_replace(' ', '-', $_POST['id'].'.jpg'))

IPB php function works but is slow. SQL needs to be faster

I'm only using a small part of this function actually but I wanted to post it all to provide the big picture. There is a part of the query in this function that finds recent attachments a user has posted to the forums. The block is on the user profile. IT works but the problem is ... it's VERY slow!! Core attachments locks up for 30+ seconds and makes my site unusable.
Any one who could help it would be much appreciated.
private function getAttImages($limit, $forumIds = 0, $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null)
{
$fids = '';
if ($forumIds)
{
$r = '';
if ($fidsReverse)
{
$r = ' NOT ';
}
if (is_array($forumIds))
{
$forumIds = implode(',', $forumIds);
}
$fids = ' AND forums_topics.forum_id ' . $r . ' IN (' . $forumIds . ')';
}
$tids = '';
if ($topicIds)
{
$tids = ' AND forums_topics.tid IN (' . $topicIds . ')';
}
$mids = '';
if ($membersIds)
{
$mids = ' AND core_attachments.attach_member_id IN (' . $membersIds . ')';
}
$whereT = array();
$joinsT = array();
$findInPosts = ' AND ' . \IPS\Db::i()->findInSet('queued', array('0'));
$joinsT[] = array(
'select' => 'forums_posts.*',
'from' => 'forums_posts',
'where' => array("forums_posts.pid=core_attachments_map.id2" . $findInPosts),
);
$findInTopics = ' AND ' . \IPS\Db::i()->findInSet('approved', array('1'));
$joinsT[] = array(
'select' => 'forums_topics.*',
'from' => 'forums_topics',
'where' => array("forums_topics.tid=forums_posts.topic_id" . $findInTopics . $fids . $tids),
);
$select = 'core_attachments.attach_id AS custom_data, core_attachments.*';
if ($group)
{
$select = 'core_attachments.attach_id AS custom_data, COUNT(attach_is_image) as cnt_images, SUM(attach_hits) as summ_attach_hits, core_attachments.*';
}
$joinsT[] = array(
'select' => $select,
'from' => 'core_attachments',
'where' => array('core_attachments.attach_is_image=1 AND core_attachments.attach_is_archived=0 AND core_attachments.attach_id=core_attachments_map.attachment_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_members.member_id, core_members.member_group_id, core_members.mgroup_others, core_members.name, core_members.members_seo_name',
'from' => 'core_members',
'where' => array('core_attachments.attach_member_id=core_members.member_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_permission_index.perm_id',
'from' => 'core_permission_index',
'where' => array("core_permission_index.app='forums' AND core_permission_index.perm_type='forum' AND core_permission_index.perm_type_id=forums_topics.forum_id"),
);
$groupT = $group;
$whereT[] = array(
"core_attachments_map.location_key='forums_Forums' AND " .
\IPS\Db::i()->findInSet('perm_view', array_merge(array(\IPS\Member::loggedIn()->member_group_id), array_filter(explode(',', \IPS\Member::loggedIn()->mgroup_others)))) . " OR perm_view='*'" .
$fids . $tids . $mids
);
$table = new \IPS\Helpers\Table\Db(
'core_attachments_map',
\IPS\Http\Url::internal('app=core&module=system&controller=nbattachpictures', 'front', 'nbattachpictures'),
$whereT,
$groupT
);
$table->joins = $joinsT;
$table->limit = $limit;
$table->sortBy = $order;
$table->sortDirection = $sort;
$table->rowsTemplate = array(\IPS\Theme::i()->getTemplate('plugins', 'core', 'global'), 'nbAttachmentsBlocksRows');
$table->parsers = array(
'custom_data' => function( $val, $row )
{
return array(
'topic_data' => \IPS\Http\Url::internal("app=forums&module=forums&controller=topic&id={$row['tid']}", 'front', 'forums_topic', array($row['title_seo'])),
'summ_attach_hits' => $row['summ_attach_hits'],
'jewel' => $this->attachJewel($row['summ_attach_hits']),
);
},
);
return $table;
}

How to loop through an associative array?

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
}
}

How can I fix this query to return only items with a certain value in its subarray?

I'm trying to modify a voting script(Thumbsup) I need this query to only return only array items that have their 'cat' => '1' in the subarray (proper term?)
<?php $items = ThumbsUp::items()->get() ?>
Here's an example of the live generated array from my database
array (
0 =>
array (
'id' => 1,
'name' => 'a',
'cat' => '1',
),
1 =>
array (
'id' => 2,
'name' => 'b',
'cat' => '2',
),
2 =>
array (
'id' => 3,
'name' => 'c',
'cat' => '2',
),
)
Is this possible by just modifying the query?
edit: heres function get()
public function get()
{
// Start building the query
$sql = 'SELECT id, name, url, cat, closed, date, votes_up, votes_down, ';
$sql .= 'votes_up - votes_down AS votes_balance, ';
$sql .= 'votes_up + votes_down AS votes_total, ';
$sql .= 'votes_up / (votes_up + votes_down) * 100 AS votes_pct_up, ';
$sql .= 'votes_down / (votes_up + votes_down) * 100 AS votes_pct_down ';
$sql .= 'FROM '.ThumbsUp::config('database_table_prefix').'items ';
// Select only either open or closed items
if ($this->closed !== NULL)
{
$where[] = 'closed = '.(int) $this->closed;
}
// Select only either open or closed items
if ($this->name !== NULL)
{
// Note: substr() is used to chop off the wrapping quotes
$where[] = 'name LIKE "%'.substr(ThumbsUp::db()->quote($this->name), 1, -1).'%"';
}
// Append all query conditions if any
if ( ! empty($where))
{
$sql .= ' WHERE '.implode(' AND ', $where);
}
// We need to order the results
if ($this->orderby)
{
$sql .= ' ORDER BY '.$this->orderby;
}
else
{
// Default order
$sql .= ' ORDER BY name ';
}
// A limit has been set
if ($this->limit)
{
$sql .= ' LIMIT '.(int) $this->limit;
}
// Wrap this in an try/catch block just in case something goes wrong
try
{
// Execute the query
$sth = ThumbsUp::db()->prepare($sql);
$sth->execute(array($this->name));
}
catch (PDOException $e)
{
// Rethrow the exception in debug mode
if (ThumbsUp::config('debug'))
throw $e;
// Otherwise, fail silently and just return an empty item array
return array();
}
// Initialize the items array that will be returned
$items = array();
// Fetch all results
while ($row = $sth->fetch(PDO::FETCH_OBJ))
{
// Return an item_id => item_name array
$items[] = array(
'id' => (int) $row->id,
'name' => $row->name,
'url' => $row->url,
'cat' => $row->cat,
'closed' => (bool) $row->closed,
'date' => (int) $row->date,
'votes_up' => (int) $row->votes_up,
'votes_down' => (int) $row->votes_down,
'votes_pct_up' => (float) $row->votes_pct_up,
'votes_pct_down' => (float) $row->votes_pct_down,
'votes_balance' => (int) $row->votes_balance,
'votes_total' => (int) $row->votes_total,
);
}
return $items;
}
thanks.
You can easily modify "get()" to add the desired functionality:
public function get($cat = null)
{
$where = array();
if ($cat !== null) {
$where[] = 'cat = '. (int) $cat;
}
// ... original code ...
}
Usage:
$items = ThumbsUp::items()->get(1);

Categories