I'm inserting some values from a json decoded response to my database, but some of the values somehow get inserted not only in their own rows, but also in other rows that had some of those values. So for example if a row had its own audio, it retains its audio, but it also gets fed with some other rows' video/photo/graffiti. However, those posts that didn't have attachments, retain those fields empty. It's a very weird behavior, and I'm already lost in those loops.
foreach ( $response->posts as $key => $element ) {
$comment_id = $element->id;
$user_id = $element->from_id;
$usersget = $var_hidden_from_this_example;
$user_name = $var_hidden_from_this_example_2;
$user_photo = $var_hidden_from_this_example_3;
$comment_text = $response->posts[$key]->text;
$comment_date = date('Y-m-d H:i:s', $response->posts[$key]->date);
if ( !isset ($element->attachments) ) {
$photo = $graffiti = $video = $audio = null;
}
else {
foreach ( $element->attachments as $key_att => $attachment ) {
if ( $attachment->type == 'photo' ) {
if ( $attachment->photo->album_id == $example_only ) {
$graffitis = array();
$graffitis[] = $attachment->photo->$example_var;
}
else {
$photos = array();
$photos[] = $attachment->photo->$example_var;
}
}
if ( $attachment->type == 'video' ) {
$videos = array();
$videos[] = $example_var2;
}
if ( $attachment->type == 'audio' ) {
$audios = array();
$audios[] = $example_var3;
}
}
if ( isset ($photos) ) {
$photo = implode('\n', $photos);
}
if ( isset ($graffitis) ) {
$graffiti = implode('\n', $graffitis);
}
if ( isset ($videos) ) {
$video = implode('\n', $videos);
}
if ( isset ($audios) ) {
$audio = implode('\n', $audios);
}
}
$data = [
'comment_id' => $comment_id,
'user_id' => $user_id,
'user_name' => $user_name,
'user_photo' => $user_photo,
'url' => $referer,
'comment_text' => $comment_text,
'comment_date' => $comment_date,
'photo' => $photo,
'graffiti' => $graffiti,
'video' => $video,
'audio' => $audio,
];
$sql = "INSERT INTO level_1 (comment_id, user_id, user_name, user_photo, url, comment_text, comment_date, photo, graffiti, video, audio) VALUES (:comment_id, :user_id, :user_name, :user_photo, :url, :comment_text, :comment_date, :photo, :graffiti, :video, :audio)";
$pdo->prepare($sql)->execute($data);
}
In other words, the values photo, graffiti, video, and audio get inserted not only in the respective rows, but the same values get inserted in all table rows that didn't have their own values of such kind (except rows that didn't have any of those - they remain empty as expected).
As was pointed out in the comments, you are not re-initialising your $graffitis arrays etc. unless you see an attachment of that type. So for an element that has no videos, it gets the videos from the previous element that had videos. Try rewriting your loop like this:
$graffitis = $photos = $videos = $audios = array();
foreach ( $element->attachments as $key_att => $attachment ) {
if ( $attachment->type == 'photo' ) {
if ( $attachment->photo->album_id == $example_only ) {
$graffitis[] = $attachment->photo->$example_var;
}
else {
$photos[] = $attachment->photo->$example_var;
}
}
if ( $attachment->type == 'video' ) {
$videos[] = $example_var2;
}
if ( $attachment->type == 'audio' ) {
$audios[] = $example_var3;
}
}
Related
I have an array that I will insert into the item table, here I use multiple inserts
Array
(
[0] => Array
(
[id_service] => 2
[tracking_number] => RJC219384044389234035
)
[1] => Array
(
[id_service] => 1
[tracking_number] => RJC749944771469498146
)
)
in the item table, there is already id_service: 2
how to make validation, when one of the input is already in the item table, then all the input is false so it fails?
my code
public function nyobain()
{
$resi = $this->input->post('kode'); //tracking_number
$expld = explode(' ', $resi);
$data = $this->M_outbound_destinasi->dbGet($expld); //get 'id_service' where tracking_number
// $db = $this->db->query("SELECT id_service FROM `tabel_items`")->result();
// foreach ($db $key) {
// $temp=array($key->id_service);
// }
// how to cek ? if id_service already in the item table
foreach ($data as $key) {
$idnya = $key['id_service'];
$id_outbound = $key['id_outbound'];
$id_indes = $key['id_indes'];
$id_outbag = $key['id_outbag'];
$data_insert = array(
'jenis' => 'outbound-destinasi',
'id_service' => $idnya,
'id_indes' => $id_indes,
'id_outbound' => $id_outbound,
'id_outbag' => $id_outbag,
'id_admin' => $this->session->userdata('ses_id')
);
$this->db->insert('tabel_items', $data_insert);
}
echo json_encode($data);
}
You can use in_array to achieve this
public function nyobain(){
$resi = $this->input->post('kode');
$expld = explode(' ', $resi);
$data = $this->M_outbound_destinasi->dbGet($expld);
$db = $this->db->query("SELECT id_service FROM `tabel_items`")->result();
if(isset($data) && $data !== ''){//check if $data has a value and it not null
if (in_array($data ,$db, true)) {
return $data.'already exists in the DB!';
}else{
foreach ($data as $key) {
$idnya = $key['id_service'];
$id_outbound = $key['id_outbound'];
$id_indes = $key['id_indes'];
$id_outbag = $key['id_outbag'];
$data_insert = [
'jenis' => 'outbound-destinasi',
'id_service' => $idnya,
'id_indes' => $id_indes,
'id_outbound' => $id_outbound,
'id_outbag' => $id_outbag,
'id_admin' => $this->session->userdata('ses_id')
];
$this->db->insert('tabel_items', $data_insert);
}
return json_encode($data);
}
}
}
i have a query inside a for loop that getting the product name of every array element. Now in every element of my array, i have an ID, where i want to concat all product names with the-same shipping_id.
Here i have my array with values like these:
Array name:id with values of:
Array
(
[0] => Array
(
[product_id] => 1
[shipping_id] => 1
)
[1] => Array
(
[product_id] => 2
[shipping_id] => 1
)
[2] => Array
(
[product_id] => 1
[shipping_id] => 2
)
)
now i made this code with these:
$first = true;
$temp_ship_id = "";
$product_list = "";
foreach ($ids as $product) {
$productname = $this->getproductname($product[0][product_id]);
// if($first) {
// $temp_ship_id = $product[0][shipping_id];
// $first = false;
// }
// if($product[0][shipping_id] == $temp_ship_id) {
// $product_list .= $productname.";
// } else {
// $product_list .= $productname.";
// //$product_list = "";
// $temp_ship_id = $product[0]->shipping_id;
// }
}
public function getproductname($product_id) {
$product = DB::table('products')->select('product_name')
->where(['products.product_id'=>$product_id])
->first();
return $product->product_name;
}
what am i doing is, i am getting the first shipping id and store it and i made a condition if they are thesame then i go concat the productname but, i see my logic is bad.
Please help me in other way. Something like This line of code to begin with:
foreach ($ids as $product) {
$productname = $this->getproductname($product[0][product_id]);
//code for concat goes here
}
public function getproductname($product_id) {
$product = DB::table('products')->select('product_name')
->where(['products.product_id'=>$product_id])
->first();
return $product->product_name;
}
Adjust below to your actual data, let me know if you have questions.
<?php
$concat = array();
$array = array( array( 'product_id'=>1, 'shipping_id'=>1, 'product_name' => 'a' ), array( 'product_id'=>2, 'shipping_id'=>1, 'product_name' => 'b' ), array( 'product_id'=>3, 'shipping_id'=>2, 'product_name' => 'c' ), array( 'product_id'=>4, 'shipping_id'=>1, 'product_name' => 'd' ) );
foreach( $array as $row ) {
if( isset( $concat[ $row['shipping_id'] ] ) ) {
$concat[ $row['shipping_id'] ] .= ',' . $row['product_name'];
} else {
$concat[ $row['shipping_id'] ] .= $row['product_name'];
}
}
var_dump( $concat );
?>
In this code filter, search and pagination not functioning i have tried myself but it didn't work so please check the code give me any solution or any reference regarding to this query. Even any related to this code files or docs it will be helpful for me to pursue the concept
<?php
mb_internal_encoding('UTF-8');
$database = 'test';
$collection = 'user';
/**
* MongoDB connection
*/
try{
// Connecting to server
$m = new MongoClient( );
}catch(MongoConnectionException $connectionException){
print $connectionException;
exit;
}
$m_collection = $m->$database->$collection;
$input = $fields = $totalRecords = $data = array();
$input = & $_REQUEST;
$fields = array('id', 'name', 'email', 'gender,');
// Input method (use $_GET, $_POST or $_REQUEST)
/**
* Handle requested DataProps
*/
// Number of columns being displayed (useful for getting individual column search info)
$iColumns = & $input['iColumns'];
// Get mDataProp values assigned for each table column
$dataProps = array();
for ($i = 0; $i < $iColumns; $i++) {
$var = 'mDataProp_'.$i;
if (!empty($input[$var]) && $input[$var] != 'null') {
$dataProps[$i] = $input[$var];
}
}
$searchTermsAny = array();
$searchTermsAll = array();
if ( !empty($input['sSearch']) ) {
$sSearch = $input['sSearch'];
for ( $i=0 ; $i < $iColumns ; $i++ ) {
if ($input['bSearchable_'.$i] == 'true') {
if ($input['bRegex'] == 'true') {
$sRegex = str_replace('/', '\/', $sSearch);
} else {
$sRegex = preg_quote($sSearch, '/');
}
$searchTermsAny[] = array(
$dataProps[$i] => new MongoRegex( '/'.$sRegex.'/i' )
);
}
}
}
// Individual column filtering
for ( $i=0 ; $i < $iColumns ; $i++ ) {
if ( $input['bSearchable_'.$i] == 'true' && $input['sSearch_'.$i] != '' ) {
if ($input['bRegex_'.$i] == 'true') {
$sRegex = str_replace('/', '\/', $input['sSearch_'.$i]);
} else {
$sRegex = preg_quote($input['sSearch_'.$i], '/');
}
$searchTermsAll[ $dataProps[$i] ] = new MongoRegex( '/'.$sRegex.'/i' );
}
}
$searchTerms = $searchTermsAll;
if (!empty($searchTermsAny)) {
$searchTerms['$or'] = $searchTermsAny;
}
$totalRecords =$m_collection->count();
$cursor = $m_collection->find($searchTerms, $fields);
/**
* Paging
*/
if ( isset( $input['iDisplayStart'] ) && $input['iDisplayLength'] != '-1' ) {
$cursor->limit( $input['iDisplayLength'] )->skip( $input['iDisplayStart'] );
}
/**
* Ordering
*/
if ( isset($input['iSortCol_0']) ) {
$sort_fields = array();
for ( $i=0 ; $i<intval( $input['iSortingCols'] ) ; $i++ ) {
if ( $input[ 'bSortable_'.intval($input['iSortCol_'.$i]) ] == 'true' ) {
$field = $dataProps[ intval( $input['iSortCol_'.$i] ) ];
$order = ( $input['sSortDir_'.$i]=='desc' ? -1 : 1 );
$sort_fields[$field] = $order;
}
}
$cursor->sort($sort_fields);
}
foreach ( $cursor as $doc )
{ $name = ''.$doc['name'].'';
$data[] = array($name, $doc['email'], $doc['gender]);
}
/**
* Output
*/
$json_data = array(
"draw"=> intval( $input['draw'] ),
"recordsTotal" =>intval ($totalRecords),
"recordsFiltered" => intval($totalRecords),
"data" => $data
);
echo json_encode( $json_data );
And also i need to Join two tables as given below.
Table 1
Table 2
I am doing it like:
$('#datatable_emp_details').dataTable({
"sServerMethod": "POST",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "get_data.php"
});
get_data.php:
<?php
$mongo = new MongoClient();
$database = $mongo->selectDb('dbtest');
$collection = $database->selectCollection('empDetails');
$skip = (int)$_REQUEST['iDisplayStart'];
$limit = (int)$_REQUEST['iDisplayLength'];
$search = $_REQUEST['sSearch'];
$sortIndex = $_REQUEST['iSortCol_0'];
$sortArray = array('emp_id', 'first_name', 'last_name', 'position', 'email', 'office', 'start_date', 'age', 'salary', 'projects'
);
$sortByCol = $sortArray[$sortIndex];
$sortTypeTxt= $_REQUEST['sSortDir_0']; // asc/desc
$sortType = -1;
if( $sortTypeTxt == 'asc' )
{
$sortType = 1;
}
if( $search != '' )
{
$condtion = array(
'$or' => array(
array('emp_id' => $search),
array('first_name'=> new MongoRegex('/'. $search .'/i')), // i for case insensitive
array('last_name' => new MongoRegex('/'. $search .'/i')),
array('position' => new MongoRegex('/'. $search .'/i')),
array('email' => new MongoRegex('/'. $search .'/i')),
array('office' => new MongoRegex('/'. $search .'/i')),
array('start_date'=> new MongoRegex('/'. $search .'/i')),
array('age' => new MongoRegex('/'. $search .'/i')),
array('salary' => new MongoRegex('/'. $search .'/i')),
array('projects' => new MongoRegex('/'. $search .'/i'))
)
);
$resultSet = $collection->find($condtion)->limit($limit)->skip($skip)->sort(array($sortByCol => $sortType));
}
else
{
$resultSet = $collection->find()->limit($limit)->skip($skip)->sort(array($sortByCol => $sortType))->sort(array($sortByCol => $sortType));
}
$data = array();
if( count( $resultSet ) > 0 )
{
foreach ($resultSet as $document)
{
$data[] = $document;
}
}
$resultSet = $collection->find();
$iTotal = count($resultSet);
$rec = array(
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iTotal,
'aaData' => array()
);
$k=0;
if (isset($data) && is_array($data)) {
foreach ($data as $item) {
$rec['aaData'][$k] = array(
0 => $item['emp_id'],
1 => $item['first_name'],
2 => $item['last_name'],
3 => $item['position'],
4 => $item['email'],
5 => $item['office'],
6 => $item['start_date'],
7 => $item['age'],
8 => $item['salary'],
9 => $item['projects'],
10 => 'Edit | Delete'
);
$k++;
}
}
echo json_encode($rec);
exit;
?>
Github repository link
I have two table ad_post and ad_img . One ad_post row has many images in ad_img. I am trying to execute 2 queries together and than combine at the end. but
table:ad_images
colums (img_id, ad_id, img_name)
table : ad_post
colums(id, user_id, title, price, cat, condit, description, vid)
Relationship
ad_post (1)------>(many)ad_images
public function read_ads()
{
$this;
$this->sql = 'SELECT ad_post.id,ad_post.user_id,ad_post.title,ad_post.price,
sub_cat.s_cat_name,ad_post.condit,ad_post.description,ad_post.vid FROM ad_post,sub_cat
where sub_cat.id=ad_post.cat';
$sql1 = 'SELECT `img_id`,`img_name` FROM `ad_images` WHERE ad_id=?';
$stmt = $this->con->prepare ( $this->sql );
$stmt1 = $this->con->prepare ( $sql1 );
if ($stmt === false) {
trigger_error ( 'Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR );
}
// STMT
$stmt->execute ();
$stmt->store_result ();
$stmt->bind_result ( $id, $uId, $title, $price, $cat, $usage, $desc, $vid );
// STMT1
// $ad =AdPost::__getAll('','','','','','','','');
// $ad = Array();
$img = Array ();
$count = 0;
$count = 0;
$ads_img = Array ();
$a_img = Array ();
while ( $stmt->fetch () != NULL ) {
$stmt1->bind_param ( 'i', $id );
$stmt1->execute ();
$stmt1->store_result ();
$stmt1->bind_result ( $img_id, $img_name );
while ( $stmt1->fetch () != NULL ) {
echo $img_id;
$a_img = Array (
'img_id' => $img_id,
'img_name' => $img_name
);
try {
$ads_img [$count] = $a_img;
} catch ( Exception $exc ) {
echo $exc->getTraceAsString ();
}
}
$count ++;
$ad_set = Array (
'id' => $id,
'uid' => $uId,
'title' => $title,
'price' => $price,
'cat' => $cat,
'usage' => $usage,
'desc' => $desc,
'img_name' => $a_img
);
try {
$ads [$count] = $ad_set;
} catch ( Exception $exc ) {
echo $exc->getTraceAsString ();
}
$count ++;
}
$stmt->free_result ();
$stmt->close ();
return $ads;
}
I have got the ids of ads now i want to save imgs in array of $ad_set
The values of image array are returning null
Here is the code to check if the contact_id is present in the pool of particular user's pool
function checkid()
{
$conn = connectPDO();
$query = "SELECT contact_id FROM contacts WHERE contact_by = :cby";
$st = $conn->prepare( $query );
$st->bindValue( ':cby', $this->contact_by, PDO::PARAM_INT );
$st->execute();
$row = $st->fetchALL();
$conn = null;
print_r($this->contact_id); //1
print_r($row); //Array ( [0] => Array ( [contact_id] => 1 [0] => 1 ) [1] => Array ( [contact_id] => 3 [0] => 3 ) )
if( !in_array( $this->contact_id, $row ))
{
echo 'You are not authorised to update the details of this contact';
}
}
Here is the url:
http://localhost/contmanager/home.php?action=update&contactid=1
One thing i noticed is that, when i use fetch instead of fetchall, it works fine for contact_id '1' but fails when using fetchALL.
in_array not works for multidimentional array's, A workaroud will be:
foreach( $row as $each ){ #collect all the ids in an array
$temp[] = $each['contact_id'];
}
Then check for in_array:
if( !in_array( $this->contact_id, $temp )){
//your code here
}
use this function for multidimentional array's :
function in_multiarray($elem, $array)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom] == $elem)
return true;
else
if(is_array($array[$bottom]))
if(in_multiarray($elem, ($array[$bottom])))
return true;
$bottom++;
}
return false;
}
example :
$array = array( array( 'contact_id' => '1' , 1 ) , array( 'contact_id' => '3' , 3 ) );
var_dump( in_multiarray( 1 , $array ) );