Implode data from an array in an array - php

Goal : Get favorited posts IDs from authors ID.
Authors ID :
$currentid = $current_user->ID;
$fav_author_list = bp_follow_get_following( array( 'user_id' => $currentid ) );
echo implode(' ', $fav_author_list);
Result : 1, 45, 9
Favorited Posts ID from one specific Author ID (1) :
$authorID = "1";
$ok = get_user_favorites($authorID, $site_id);
echo implode(' ', $ok);
Result : 845, 895
I want Favorited Posts ID from multiple Authors ID (1, 45, 9) : NOT WORKING
$ok = get_user_favorites($fav_author_list, $site_id);
echo implode(' ', $ok);
$fav_author_list should be an unique value and this is my problem because I want get_user_favorites from multiple values
get_user_favorites function :
function get_user_favorites($user_id = null, $site_id = null, $filters = null)
{
global $blog_id;
$site_id = ( is_multisite() && is_null($site_id) ) ? $blog_id : $site_id;
if ( !is_multisite() ) $site_id = 1;
$favorites = new UserFavorites($user_id, $site_id, $links = false, $filters);
return $favorites->getFavoritesArray();
}
EDIT :
$currentid = $current_user->ID;
$fav_author_list = bp_follow_get_following( array( 'user_id' => $currentid ) );
$ok = get_user_favorites($fav_author_list[0]);
foreach ($ok as $name => $age) {
echo $name = $age;
}
I succeed to get some results from $fav_author_list[0] and $fav_author_list[1] etc, what I want is to get ALL results in same time

Related

Inserting array of data in database

I have two arrays of values:
First array contain user id's:
Array ([0]=>1 [1]=>2 [2]=>3 [3]=>4 [4]=>5 [5]=>6)
Second array contain attendance status:
Array([0]=>Present [1]=>Absent [2]=>Absent [3]=>Present [4]=>Absent [5]=>Present)
I want to insert these values in the database in separate rows like this:
U_id Status
1 Present
2 Absent
3 Absent
4 Present
5 Absent
6 Present
Currently, I am using this code to insert values in database.
My Controller Code:
public function usr_att(){
if(isset($_POST['submit'])){
$uid = $_POST['uid'];
$status= $_POST['stat'];
$id = implode("," , $uid );
$status = implode("," , $status );
$data = array (
'u_id' => $id,
'status' => $status
);
$this->db->insert('attendence' , $data);
redirect("usr/usr_list", "refresh");
}
}
But this code inserts data like this:
U_id Status
1 Present,Absent,Absent,Present,Absent,Present
How can I insert these values in separate rows using CodeIgniter?
Simply you can do like this
public function usr_att()
{
if(isset($_POST['submit']))
{
$uid = $_POST['uid'];
$status = $_POST['stat'];
foreach ($uid as $key => $item)
{
$data = array (
'u_id' => $item,
'status' => $status[$key]
);
$this->db->insert('attendence' , $data);
}
redirect("usr/usr_list", "refresh");
}
}
For your intended purpose, once you have the values for $uid and $stat in an array, then you could do this:
<?php
// You have your u_id values in an array
$uid = array('1','2','3','4','5','6');
// You have your status values in an array
$stat = array('Present', 'Absent', 'Absent', 'Present', 'Absent', 'Present');
// As long as the number of u_id values and status values are the same
if( count($uid) == count($stat) )
{
// Use the count of uid values and loop through
for( $x = 0; $x <= count($uid) -1; $x++ )
{
// Entering each on in the database
$this->db->insert('attendence', array(
'u_id' => $uid[$x],
'status' => $stat[$x]
));
}
}

Pagination issue with WP_List_table in WordPress

I'm developing a plugin for WordPress. I use WP_List_Table which output rows from database nicely.
The issue I have is the pagination. If I have let's say 200 rows in the database and I set it to only display 50 rows per page, this works and I do get 1 of 4 pages.
On page 1 It displays ID 1 to ID 50. But when I click on page 2 it displays ID 2 to ID 51. So it only jumps 1 row and not 50. Where's the issue?
This will handle the data:
function prepare_items() {
global $wpdb;
/* Select project for user */
$table_name2 = $wpdb->prefix . 'project_name';
$current_user = wp_get_current_user();
$sql2 = "SELECT * FROM " . $wpdb->prefix . "project_name WHERE alloweduser = " . $current_user->ID;
$results2 = $wpdb->get_results($sql2) or die(mysql_error());
foreach( $results2 as $result2 ) {
$table_name = $wpdb->prefix . "project_name_" . $result2->projectname;
/* Define how many rows to show per page */
$per_page = 50;
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
// here we configure table headers, defined in our methods
$this->_column_headers = array($columns, $hidden, $sortable);
// [OPTIONAL] process bulk action if any
$this->process_bulk_action();
// will be used in pagination settings
$total_items = $wpdb->get_var("SELECT COUNT(cid) FROM $table_name");
// prepare query params, as usual current page, order by and order direction
$paged = isset($_REQUEST['paged']) ? max(0, intval($_REQUEST['paged']) - 0) : 0;
$orderby = (isset($_REQUEST['orderby']) && in_array($_REQUEST['orderby'], array_keys($this->get_sortable_columns()))) ? $_REQUEST['orderby'] : 'cid';
$order = (isset($_REQUEST['order']) && in_array($_REQUEST['order'], array('ASC', 'DESC'))) ? $_REQUEST['order'] : 'ASC';
// Define $items array
// notice that last argument is ARRAY_A, so we will retrieve array
$this->items = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name ORDER BY $orderby $order LIMIT %d OFFSET %d", $per_page, $paged), ARRAY_A);
// configure pagination
$this->set_pagination_args(array(
'total_items' => $total_items, // total items defined above
'per_page' => $per_page, // per page constant defined at top of method
'total_pages' => ceil($total_items / $per_page) // calculate pages count
));
}
}
}
This will output the data:
function custom_table_example_submissions_page_handler() {
global $wpdb;
$table = new Custom_Table_Example_List_Table();
$table->prepare_items();
$message = '';
if ('delete' === $table->current_action()) {
$message = '<div class="updated below-h2" id="message"><p>' . sprintf(__('Deleted %d submission(s).', 'custom_table_example'), count($_REQUEST['id'])) . '</p></div>';
}
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit">
<br></div>
<h2><?php _e('Submissions', 'custom_table_example')?>
</h2>
<?php echo $message; ?>
<form id="submissions-table" method="GET">
<input type="hidden" name="page" value="<?php echo $_REQUEST['page']; ?>"/>
<?php //$table->display(array('contributorname', 'email')); ?>
<?php $table->display(); ?>
</form>
</div>
<?php
}
Update:
get_columns:
function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />', //Render a checkbox instead of text
'name' => __('Name', 'custom_table_example'),
'upload' => __('Upload', 'custom_table_example'),
'upload2' => __('Upload', 'custom_table_example'),
'upload3' => __('Upload', 'custom_table_example'),
'upload4' => __('Upload', 'custom_table_example'),
'rate' => __('Rate', 'custom_table_example'),
);
return $columns;
}
$this->items is retrieved from:
https://core.trac.wordpress.org/browser/tags/4.0.1/src//wp-admin/includes/class-wp-list-table.php#L0
It's called with:
if (!class_exists('WP_List_Table')) {
require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}
I managed to solve it and answer my own question.
The issue was here:
$paged = isset($_REQUEST['paged']) ? max(0, intval($_REQUEST['paged']) - 0) : 0;
Since I want to output 50 rows per page I simply added -1 to $_REQUEST['paged'] and added * 50 which means that on page 1 row 1-50 is displayed and on page 2 rows 51-100 is displayed since 2*50 is 100 and so on.
Correct solutions is this:
$paged = isset($_REQUEST['paged']) ? max(0, intval($_REQUEST['paged'] -1) * 50) : 0;
I have same issue in my project so solution is here
$per_page = 5;
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
$this->process_bulk_action();
$paged = isset($_REQUEST['paged']) ? max(0, intval($_REQUEST['paged'] -1) * $per_page) : 0;
I hope Now your problem will be solve
$found_data = array_slice($this->table_data(),(($current_page-1)*$per_page),$per_page);
$this->items = $found_data;
Use above mention code in your prepare_items(). It devides your list of data into the chunks.

Something not working as expected in this PHP function

I am trying to pull data from MySQL and this supposed to show complete data but this is showing only one row. This is supposed to show all rows of users. I don’t know what I did wrong:
Here is the code:
function getCashoutRequests($uid, $limit) {
if (!empty( $limit )) {
$query = mysql_query( '' . 'SELECT * FROM cashouts WHERE uid = ' . $uid . ' ORDER BY id DESC LIMIT ' . $limit );
}
else {
$query = mysql_query( '' . 'SELECT * FROM cashouts WHERE uid = ' . $uid . ' ORDER BY id DESC' );
}
if (mysql_num_rows( $query )) {
if ($row = mysql_fetch_object( $query )) {
$row->id;
$amount = $row->amount;
$status = $row->status;
$client_notes = nl2br( $row->user_notes );
$admin_notes = nl2br( $row->admin_notes );
$request_date = $row->request_date;
$payment_date = $row->payment_date;
$fee = $row->fee;
$priority = $hid = $row->priority;
$method = $row->method;
if ($payment_date != '0000-00-00 00:00:00') {
$payment_date = date( 'd M, Y', strtotime( $payment_date ) );
}
$request_date = date( 'd M, Y', strtotime( $request_date ) );
$payHistory []= array( 'id' => $hid, 'cash' => $amount, 'status' => $status, 'method' => $method, 'client_notes' => $client_notes, 'admin_notes' => $admin_notes, 'date' => $request_date, 'payment_date' => $payment_date, 'fee' => $fee, 'priority' => $priority );
}
return $payHistory;
}
return false;
}
On this line you have if:
if ($row = mysql_fetch_object( $query )) {
If you use if that would only go to the first value since if simply tests a condition once. Instead try while like this:
while ($row = mysql_fetch_object( $query )) {
As explained in the PHP manual entry for while:
The meaning of a while statement is simple. It tells PHP to execute
the nested statement(s) repeatedly, as long as the while expression
evaluates to TRUE.

MySQL Search from Multiple User supplied where clause - Fix and Better Algorithm

I want to run search query where i have multiple where clause. and multiple depends upon the user argument.
for example i mean, Search may depend on 1 column, 2 column, 3 column or 6 column in my case, and i don't want to run if-elseif-else statement with all column probability. So, i have just built up below function, but i am stuck with and that comes in between multiple column search case. Below is my code :-
function listPlayer($player="player_guest", $group="group_guest",
$weapon="weapon_guest", $point="point_guest", $power="level_guest",
$status="status_guest") {
$lePlayer = (isset($player) && $player != "player_guest") ?
'player= '.$mysqli->real_escape_string($player).' and' : '';
$leGroup = (isset($group) && $group != "group_guest") ?
'group= '.$mysqli->real_escape_string($group).' and' : '';
$leWeapon = (isset($weapon) && $weapon != "weapon_guest") ?
'weapon= '.$mysqli->real_escape_string($weapon).' and' : '';
$lePoint = (isset($point) && $point != "point_guest") ?
'point= '.$mysqli->real_escape_string($point).' and' : '';
$lePower = (isset($power) && $power != "level_guest") ?
'level= '.$mysqli->real_escape_string($power).' and' : '';
$leStatus = (isset($status) && $status != "status_guest") ?
'status= '.$mysqli->real_escape_string($status).' and' : '';
$query = "Select pid, name from game where {$lePlayer} {$leGroup} {$leWeapon} {$lePoint} {$lePower} {$leStatus} ";
$runQuery = $mysqli->query($query);
}
but problem is and at the end. If i use them, than i have extra and at the end, and if i don't use them that's again an error.
Can some one help me to fix and find better way to do it.
Update: My Update Code that works if some one needs them Thanks to Barmar
function listPlayer($player="player_guest", $group="group_guest",
$weapon="weapon_guest", $point="point_guest", $power="level_guest",
$status="status_guest") {
$lePlayer = (isset($player) && $player != "player_guest") ?
'player= '.$mysqli->real_escape_string($player) : '' ;
$leGroup = (isset($group) && $group != "group_guest") ?
'group= '.$mysqli->real_escape_string($group) : '' ;
$leWeapon = (isset($weapon) && $weapon != "weapon_guest") ?
'weapon= '.$mysqli->real_escape_string($weapon) : '' ;
$lePoint = (isset($point) && $point != "point_guest") ?
'point= '.$mysqli->real_escape_string($point) : '' ;
$lePower = (isset($power) && $power != "level_guest") ?
'level= '.$mysqli->real_escape_string($power) : '' ;
$leStatus = (isset($status) && $status != "status_guest") ?
'status= '.$mysqli->real_escape_string($status) : '' ;
$condition_array = ( $lePlayer , $leGroup , $leWeapon , $lePoint , $lePower , $leStatus)
$condition_stirng = implode(' and ', $condition_array);
$query = "Select pid, name from game where ".$condition_stirng;
$runQuery = $mysqli->query($query);
}
Update:
I got mail from someone at my email which says my code is vulnerable to SQL Injection. Here it is POC http://www.worldofhacker.com/2013/09/interesting-sql-vulnerable-code-even.html
Thanks
Put all the conditions in an array. Then combine them with:
$condition_string = implode(' and ', $condition_array);
The simple solution is to trim the "and" off at the end:
$query = substr($query, 0, strlen($query) - 3);
however a more efficient way would be to put them in a loop, like this:
$wheres = array("player_guest"=>$player, "group_guest"=>$group.....);
$query_where = "";
$i = 0;
foreach($wheres as $where=>$value){
list($condition, $null) = explode("_",$where);
if(isset($value)){
$query_where .= $condition . "='" . $mysqli->real_escape_string($value)."'";
if($i != sizeof($wheres)){
$query_where .= " and ";
}
}
$i++;
}
This is extendable for any number of conditions, and doesnt require the extra string function at the end.
Notice the $defaults is needed to make sure your conditions work. A bit repetitive, but it's all due to your function declaration.
function listPlayer(
$player="player_guest",
$group="group_guest",
$weapon="weapon_guest",
$point="point_guest",
$power="level_guest",
$status="status_guest") {
//I'm just copying whatever is in the default parameters ;)
$defaults = array(
'player' => 'player_guest',
'group' => 'group_guest',
'weapon' => 'weapon_guest',
'point' => 'point_guest',
'power' => 'level_guest',
'status' => 'status_guest'
);
//Set all user parameters into an array, easier to loop through
$data = compact(array_flip($defaults));
//Then we build conditions
$conditions = array();
foreach($data as $k => $v) {
if ($defaults[k] !== $v) {
$v = $mysqli->real_escape_string($v);
$conditions[] = "$k='$v'";
}
}
//And build query
$query = "SELECT pid, name FROM game WHERE ".implode(" AND ", $conditions);
$runQuery = $mysqli->query($query);
}
First of all I recommend you to look at PDO when you work with MySQL in PHP.
Such tasks are always simply solved with array maps.
function listPlayer($player = null, $group = null, $weapon = null, $point = null, $power = null, $status = null) {
$defaults = array(
'player' => 'player_guest',
'group' => 'group_guest',
'weapon' => 'weapon_guest',
'point' => 'point_guest',
'status' => 'status_guest',
);
$values = compact(array_keys($defaults));
$filtered = array_filter(array_diff_assoc($values, $defaults)); //firstly filtering out defaults, then - nulls.
$where = '';
foreach($filtered as $column => $value){
if($where){
$where .= ' AND ';
}
$where .= sprintf("`%s` = '%s'", $column, $mysqli->real_escape_string($value));
}
$query = "SELECT pid, name FROM game WHERE $where";
//executing...
}

How can i show sphinx search result in PHP

How is that possible to show sphinx search result via PHP
i have installed sphinx and configured but i am unable to get the result via PHP
Check the Sphinx Library : Sphinx Documentation
The Below Code Is Used To Get The Full Content From Sphinx Search Result
Now Currently We Need To Give The Id In $SQL line
<?php
echo "Welcome To Sphinx Search Site </br>";
$q = "html";
$sphx = sphinx_search("html", 0, 20);
$sphx['122'];
$ids = 122;
$sql = "SELECT post_title , post_content FROM wp_posts WHERE ID = '122'";
db();
if( !($r = mysql_query($sql)))
die("[MYSQL]".mysql_error() . mysql_errno() );
$max = $sphx['total'];
$num_rows = $sphx['docs'];
echo "<b>Displaying {$num_rows} results of {$max}</b><br /><br />";
while($row = mysql_fetch_assoc($r) ) {
echo "{$row['post_title']} <br />{$row['post_content']}<br /><hr />";
}
mysql_free_result($r);
/*
* SPHINX Search
*/
/*
* Search sites by Keywords using sphinx; with an option to search sites tags only
* #param string $q te keyword
* #param int $i id of the first result to return
* #param int $max max results to return
* #param bollen $url set to true to return matches from the 'url' column only
*
* #return string $ids comma seperated list of ids
*/
function sphinx_search($q, $i, $limit, $post_type=true){
require_once 'sphinxapi.php';
$ids = '33500';
$cl = new SphinxClient();
$cl->SetServer( "192.168.0.89" , 9667);
$cl->SetMatchMode( SPH_MATCH_EXTENDED );
$cl->SetSortMode ( SPH_SORT_RELEVANCE );
$cl->SetFieldWeights(array('post_title' => 300));
$cl->SetLimits( $i , $limit);
$q = $cl->EscapeString( $q);
//search url only
$q = $post_type ? "#post_type {$q}" : $q;
$result = $cl->Query( $q, 'sites sitesDelta' );
if ( $result === false )
error_log( '[SPHINX]Query failed: ' . $cl->GetLastError() );
elseif ( $cl->GetLastWarning() )
error_log( '[SPHINX]WARNING: ' . $cl->GetLastWarning() );
if ( !empty($result["matches"]) ){
foreach ( $result["matches"] as $doc => $docinfo )
$ids .= "$doc,";
$ids = substr( $ids, 0, -1 );
}else
return false;
return array( 'ids' => $ids, 'total' => $result['total'], 'docs' => count($result["matches"]) );
}
/*
* Connect to MySQL
*/
function db(){
if( !empty($GLOBALS['db']) ) return true;
if( !$GLOBALS['db'] = mysql_connect('localhost', 'root', '' ) ) {
die("[MYSQL]".mysql_error() . mysql_errno() );
}
elseif(!mysql_select_db('sphinxiirmulti')) {
die("[MYSQL]".mysql_error() . mysql_errno() );
}
}
?>

Categories