How to combine single row with array of data in prepared statements - php

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

Related

Items in foreach loop are somehow not unique

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

PDOStatement->bindParam doesn't work

I have some trouble with $query->bindParam. It doesn't change placeholders into values.
$options is an array:
$options['where'] = [
'id' => [ 1, 2, 3 ],
'title' => [ 'some', 'title' ]
];
$fields = '*';
$where_clauses = []; /* define empty error which could be filled with where clauses */
/* if it is a separte blog, only posts posted by it's admin should be got */
if ( Main::$current_blog_id !== 1 )
$where_clauses[] = '`author_id` IN(' . $this->blog->admin_id . ')';
/* if options have been passed */
if ( ! empty( $options ) ) {
/* if there are "where" options */
if ( ! empty( $options['where'] ) ) {
$placeholder_number = 1; /* define placeholder number */
$placeholders = []; /* create array with placeholders 'placeholder_number' => 'value' */
foreach ( $options['where'] as $field_name => $values ) {
$field_values = []; /* values that will be used to create "IN" statement */
/* fill $fild_values array with values */
foreach ( $values as $value ) {
$placeholder = ':' . $placeholder_number; /* create placeholder */
$field_values[] = $placeholder; /* add placeholder to field values */
$placeholders[ $placeholder ] = $value; /* add placeholer with it's value to common placeholders array */
$placeholder_number++; /* increase placeholder number */
}
/* turn $fields_values array into string */
$field_values = implode( ', ', $field_values );
/* create clause and put it into $where_clauses */
$where_clauses[] = '`' . $field_name . '` IN(' . $field_values . ')';
}
}
}
/* if where statement is empty */
$where_clauses =
! empty( $where_clauses ) ?
implode( ' AND ', $where_clauses ) :
1;
$query = Main::$data_base->pdo->prepare(
'SELECT ' . $fields . ' ' .
'FROM `posts` ' .
'WHERE ' . $where_clauses . ' ' .
'LIMIT ' . $posts_quantity . ';'
);
/* if there are placeholders in the query */
if ( ! empty( $placeholders ) ) {
foreach ( $placeholders as $placeholder => $value )
$query->bindParam( $placeholder, $value, PDO::PARAM_STR );
}
$query->execute();
$posts = $query->fetchAll( PDO::FETCH_ASSOC );
var_dump( $query );
return
! empty( $posts ) ?
$posts :
[];
After all of this my printed query looks like:
SELECT * FROM `posts` WHERE `id` IN(:1, :2, :3) AND `title` IN(:4, :5) LIMIT 15;
You need to define the binds like...
Array ( ':1' => 1, ':2' => 2, ':3' => 3, ':4' => 'some', ':5' => 'title' )
Also your select is incorrect...
"SELECT * FROM posts WHERE id IN(:1, :2, :3) AND title IN(:4, :5) LIMIT 15;"
You have to put AND and not && in there.
PDOStatement::bindParam doesn't modify the query string that you passed to PDO::prepare. It replaces the placeholders with the value of the variable that you bound to it in the moment you execute the statement and the query is sent to the SQL server.
This should be what you want:
$query = "SELECT * FROM posts WHERE id IN (:1, :2, :3) AND title IN (:4, :5) LIMIT 15;";
$statement = $db->prepare($query); // $db contains the connection to the database
$placeholders = array(':1' => 1, ':2' => 2, ':3' => 3, ':4' => 'some', ':5' => 'title');
foreach ($placeholders as $placeholder => $value) {
$statement->bindValue($placeholder, $value, PDO::PARAM_STR);
}
$statement->execute();
Note that I use PDOStatement::bindValue and that I modified your SQL query string (and instead of &&).
You could also do this:
$query = "SELECT * FROM posts WHERE id IN (:1, :2, :3) AND title IN (:4, :5) LIMIT 15;";
$statement = $db->prepare($query);
$placeholders = array(':1' => 1, ':2' => 2, ':3' => 3, ':4' => 'some', ':5' => 'title');
$statement->execute($placeholders);
Read about PDOStatement::execute in the docs.

Data tables filters, search Not functioning mongodb php

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

in_array not finding the value which is present?

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

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