Adding user ip to existing meta_value with single meta_id as array - mysql

I am currently getting the user IP on a slider change and sending it to the WP DB but I want to keep the DB smaller and have a single meta_id for the list of IPs.
My current code is sort of working but as it adds the new ip to the existing array something is causing it to turn into a multidimensional one and breaking it.
Here is my code.
$user_ip = $_POST['ip'];
$user_score = $_POST['sliderValue'];
$postID = $_POST['post_id'];
$currentIPs = maybe_unserialize(get_post_meta( $postID, 'user_ip'));
$currentIPs[] = $user_ip;
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
update_post_meta($postID, 'user_ip', $currentIPs);
echo var_dump($currentIPs);
}
die();
}
I have tried with add_post_meta and that works fine but it creates a new meta_id for each IP which would just make the database huge. For performance and space saving I was just one key and ID with all the values.

The function is programmed to create a new meta_id every time you use update_meta_data.
However the workaround is that you can store the IPS within same meta_id by seperating IPS with commas.
Replace
$currentIPs = maybe_unserialize(get_post_meta( $postID, 'user_ip'));
$currentIPs[] = $user_ip;
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
update_post_meta($postID, 'user_ip', $currentIPs);
With
$currentIPs = $user_ip;
$userIp = get_post_meta($postID, 'user_ip',true);
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
if (empty($userIp)) {
update_post_meta($postID, 'user_ip', $currentIPs);
} else {
$newvalue = $currentIPs .','. $userIp;
update_post_meta($postID, 'user_ip', $newvalue);
}
Later if you want these data in an array, you can use php's explode() function afterwards

Related

How to change the search action in wordpress search bar?

Create a new post and publish it.
The title is my test for search, content in it is as below:
no host route
Check what happen in wordpress database.
select post_title from wp_posts
where post_content like "%no%"
and post_content like "%route%"
and post_content like "%to%"
and post_content like "%host%";
The post named my test for search will not be in the select's result.
Type no route to host in wordpress search bar,and click enter.
The post named my test for search shown as result.
I found the reason that the webpage contain to ,in the left upper side corner ,there is a word Customize which contains the searched word to.
How to change such search action in wordpress serach bar?
I want to make the search behavior in wordpress saerch bar, for example ,when you type no route to host, equal to the following sql command.
select post_title from wp_posts where post_content like "%no%route%to%host%";
All the plugins in my wordpress.
CodePen Embedded Pens Shortcode
Crayon Syntax Highlighter
Disable Google Fonts
Quotmarks Replacer
SyntaxHighlighter Evolved
There's this addition to the SQL WHERE clause on wp-includes/class-wp-query.php:1306:
<?php
// wp-includes/class-wp-query.php:~1306
foreach ( $q['search_terms'] as $term ) {
//...
$like = $n . $wpdb->esc_like( $term ) . $n;
$search .= $wpdb->prepare( "{$searchand}(({$wpdb->posts}.post_title $like_op %s) $andor_op ({$wpdb->posts}.post_excerpt $like_op %s) $andor_op ({$wpdb->posts}.post_content $like_op %s))", $like, $like, $like );
// ...
Therefore, I'd hook into the pre_get_posts, and supply the words of the query as explicit "search_terms", since they get added into that clause, with the LIKE modifier just as you said were looking for!
So, we might do something like this:
<?php
// functions.php
function fuzzify_query(\WP_Query $q) {
if (true === $q->is_search()
&& true === property_exists($q, 'query')
&& true === key_exists('s', $q->query)
) {
$original_query = $q->query['s'];
$words = explode(' ', $original_query);
$fuzzy_words = array_map(
function($word) {
return '%'.$word.'%';
},
$words
);
$q->query_vars['search_terms'] = $fuzzy_words;
return $q;
}
return $q;
}
add_action('pre_get_posts', 'fuzzify_query', 100); // Or whatever priority your fuzziness requires!

Loop in column name MYSQL

I am using MYSQL.My table contains column name as Revenue2000,Revenue2001,Revenue2002,....,Revenue 2016,Revenue 2017
Traditional way(to select all column manually):
select Revenue2005,
Revenue2006,
Revenue2007,
Revenue2008,
Revenue2009,
Revenue2010
from table_name
Desired Way:
I want to write a Dynamic select statement .There should 2 variables "start" and "end" so that i can make it dynamic.User has the option to specify the starting year and ending year and can view the desired result.
In above case, Start year =2005
End Year=2010
Yes, it's bad database design, and the best answer would be "don't do this at all, just fix your table." Unfortunately, sometimes you're stuck with something someone else made, and can't change it for whatever reason, but you still need to accomplish something (welcome to my life). I would do it like this:
Get the years from user input and convert them to integers in case someone enters something silly/naughty. Don't depend on client-side validation. Prepared statements won't help you here because these will be used as parts of column names.
$start = (int) $_POST['start'];
$end = (int) $_POST['end'];
Do a quick sanity check to make sure that the range makes sense and should work with what's in your database.
if ($start > $end
|| $start < $lowest_year_in_your_db
|| $end > $highest_year_in_your_db) {
// quit with error
}
Then you can generate a list of columns to use in your query. Here's one way with range and array_map, but you could also just build a string with a for loop.
$columns = implode(', ', array_map(function($year) {
return "Revenue$year";
}, range($start, $end)));
$sql = "SELECT $columns FROM table_name";
Theoretically, the worst thing that should be able to happen with this is that you'd get a column that didn't exist, and your query would fail.
But really, if you have any choice about it, don't do this. Normalize your database as people have stated in the comments, or find whoever keeps adding more year columns to the database and make them do it.
As already pointed out the database design is horrible. You should really normalize it, it's worth the effort.
However if that is not possible at the moment the follow code should do exactly what you need:
// Connect to DB
$mysqli = new mysqli("localhost", "USERNAME", "PASSWORD", "DATABASE");
// Get column names
$columns = $mysqli->query('SHOW COLUMNS FROM revenue')->fetch_all();
$columnNames = array_column($columns, 0);
// Extract years from column names
$years = array_map(function($columnName) {
return (int) substr($columnName, -4);
}, $columnNames);
// Get max and min year
$maxYear = max($years);
$minYear = min($years);
// Input year start and end
$start = (int) $_POST['start']; // User-input
$end = (int) $_POST['end']; // User-input
// Avoid wrong inputs
if($start > $end || $start < $minYear || $end > $maxYear) {
die('Error');
}
// Create the SQL-query
$selectColumns = [];
for ($i = $start; $i <= $end; $i++) {
$selectColumns[] = "revenue" . $i;
}
$queryString = "SELECT " . implode(", ", $selectColumns) . " FROM TABLE";
// Run the query
// ...

Customizing user_nicename in wp_users table in wordpress

By default wordpress will santitize the contents written to user_nicename column in wp_users table. It will remove spaces, some special characters and change uppercase to lowercase. Will it be possible to update user_nicename column without sanitizations?
It is possible using the pre_user_nicename filter. You can read on it here https://developer.wordpress.org/reference/hooks/pre_user_nicename/ The filter is applied right after the nicename is sanitized, but we can still access the unsanitized data. This is from wp-includes/user.php
/*
* If a nicename is provided, remove unsafe user characters before using it.
* Otherwise build a nicename from the user_login.
*/
if ( ! empty( $userdata['user_nicename'] ) ) {
$user_nicename = sanitize_user( $userdata['user_nicename'], true );
if ( mb_strlen( $user_nicename ) > 50 ) {
return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
}
} else {
$user_nicename = mb_substr( $user_login, 0, 50 );
}
$user_nicename = sanitize_title( $user_nicename );
// Store values to save in user meta.
$meta = array();
/**
* Filters a user's nicename before the user is created or updated.
*
* #since 2.0.3
*
* #param string $user_nicename The user's nicename.
*/
$user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
$raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
You can still access the unmodified nicename entered by the user with the $userdata['user_nicename'] variable. So an example filter would go like this:
add_filter( 'pre_user_nicename', 'my_nicename_modification');
function my_nicename_modification($userdata) {
/*do anything you want with $userdata['user_nicename'] here
or leave blank if you want it saved just as the user typed it in */
return $userdata['user_nicename'];
}
This will stop $user_nicename = sanitize_title( $user_nicename ); from running, on which you can read more on here https://codex.wordpress.org/Function_Reference/sanitize_title. That is that modifies the nicename as you explained in your question. Hope this helps

MySQL and using only some results

I am trying to create a directory and having an issue calling the "listing image" in the results. The issue is that only some listings will have images, otherwise if they do not, I want them to use the default-image I have set up. When I try and add in the 'image' table to my query, it returns ONLY the results that have an image available (leaving out the other listings that do not have an image).
Here is my code:
public function search($neighborhood = null, $biz_filter = null) {
$neighborhood = $this->uri->segment(3);
$biz_filter = $this->uri->segment(4);
// SELECT
$this->db->select('*');
// MAIN TABLE TO GRAB DATA
$this->db->from('biz');
// TABLES TO JOIN
$this->db->join('city', 'city.city_id = biz.biz_cityID');
$this->db->join('zip', 'zip.zip_id = biz.biz_zipID', 'zip.zip_cityID = city.city_id');
$this->db->join('state', 'state.state_id = city.city_stateID');
$this->db->join('neighborhood', 'neighborhood.neighborhood_id = biz.biz_neighborhoodID');
$this->db->join('biz_filter', 'biz_filter.bizfilter_bizID = biz.biz_id');
$this->db->join('biz_category', 'biz_category.bizcategory_id = biz_filter.bizfilter_bizcategoryID');
if ($neighborhood != "-" AND $biz_filter != "-") {
$this->db->where('biz_category.bizcategory_slug', $biz_filter);
$this->db->where('neighborhood.neighborhood_slug', $neighborhood);
} elseif ($neighborhood != "-" AND $biz_filter == "-") {
$this->db->where('neighborhood.neighborhood_slug', $neighborhood);
} elseif ($neighborhood == "-" AND $biz_filter != "-") {
$this->db->where('biz_category.bizcategory_slug', $biz_filter);
} else {
}
// ORDER OF THE RESULTS
$this->db->group_by('biz_name asc');
// RUN QUERY
$query = $this->db->get();
// IF MORE THAN 0 ROWS ELSE DISPLAY 404 ERROR PAGE
return $query;
}
How can I add in the separate table, 'image' that holds the logo images ('image.image_file'). The 'image' table and 'biz' table are connected through the business ID i pass through each table (image.biz_id = biz.biz_id).
Anyone know how to resolve the query to work properly?
Just use
$this->db->join('image', 'image.biz_id = biz.biz_id', 'left');
To LEFT JOIN your image table. When there is no records in the table for the biz_id the image.image_file will have null values. Read here for more information.
You can use a COALESCE function to replace the "null" images with a predefined default value. Just replace your line with $this->db->select('*'); to this one:
// SELECT
$this->db->select("*, COALESCE(image.image_file, 'images/not_found.png') as my_image_file");
When you render the output make sure you use my_image_file column for the image.
On a side note: avoid using '*' in the select. Select only those columns you actually need. Selecting all columns unnecessarily increases the load on the database server resources.

Multidimensional Array insert into Mysql rows

I have an Array (twodimensional) and i insert it into my database.
My Code:
$yourArr = $_POST;
$action = $yourArr['action'];
$mysql = $yourArr['mysql'];
$total = $yourArr['total'];
unset( $yourArr['action'] , $yourArr['mysql'] , $yourArr['total'] );
foreach ($yourArr as $k => $v) {
list($type,$num) = explode('_item_',$k);
$items[$num][$type] = $v;
$pnr= $items[$num][pnr];
$pkt= $items[$num][pkt];
$desc= $items[$num][desc];
$qty= $items[$num][qty];
$price= $items[$num][price];
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
I get 5 inserts in the Database but only the 5th have the informations i want. The firsts are incomplete.
Can someone help me?
Sorry for my english.
check if You have sent vars from browser in array (like
input name="some_name[]" ...
also You can check, what You get at any time by putting var_dump($your_var) in any place in script.
good luck:)
You probably want to have your query and the 5 assignments above that outside of the foreach. Instead in a new loop which only executes once for every item instead of 5 times. Your indentation even suggests the same however your brackets do not.
Currently it is only assigning one value each time and executing a new query. After 5 times all the variables are assigned and the last inserted row finally has everything proper.
error_reporting(E_ALL);
$items = array();
foreach($yourArr as $k => $v) {
// check here if the variable is one you need
list($type, $num) = explode('_item_', $k);
$items[$num][$type] = $v;
}
foreach($items as $item) {
$pnr = mysql_real_escape_string($item['pnr']);
$pkt = mysql_real_escape_string($item['pkt']);
$desc = mysql_real_escape_string($item['desc']);
$qty = mysql_real_escape_string($item['qty']);
$price = mysql_real_escape_string($item['price']);
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
Switching on your error level to E_ALL would have hinted in such a direction, among else:
unquoted array-keys: if a constant of
the same name exists your script will
be unpredictable.
unescaped variables: malformed values
or even just containing a quote which
needs to be there will fail your
query or worse.
naïve exploding: not each $_POST-key
variable will contain the string
item and your list will fail, including subsequent use of $num