Excuse me if I ask the obvious, but I am quite mySQL illiterate .
I am referring to a standard wordpress DB install, although this is not a wordpress specific question, but more mySQL general knowledge ..
If I want to change all the values of a certain field across all posts , I usually do :
UPDATE `wp_postmeta` SET `meta_value` = replace(meta_value, 'old_value', 'new_value') WHERE `meta_key` LIKE 'my_meta_key'
The problem is as follows :
In that specific DB , the INITIAL values were inserted with a white space prefix and suffix , e.g. :
"city name"
was actually inserted as
" city name "
of course , being a PHP person, I immediately thought of the trim() command - which I found out exists also in mySQL.
SO now I thought I could just do
UPDATE `wp_postmeta` SET `meta_value` = TRIM('meta_value') WHERE `meta_key` LIKE 'my_meta_key'
But It is not working ..
What Am I doing wrong ? I know that mySQL is "ticks sensetive" ( so to speak ) But I tried both 'meta_value' and `meta_value' ( sorry, markdown limitations seems to truncate the backticks)
Doing replace(meta_value, ' ', '') is dengaurous because some cities havea spaces in their name, and LTRIM RTRIM is somewhat not working for me as well
I also know there is a way to set a variable in sql ( #my_var )
but what is the correct syntax of doing that in my case ?
SET #my_var = `meta_value`
and then
UPDATE `wp_postmeta` TRIM(#my_var) WHERE `meta_key` LIKE 'my_meta_key'
I of course know how to fix it in a php loop (with trim() ) but I would like to learn what is the best way to do it in mySQL..
To refer to the column, you need backticks:
UPDATE `wp_postmeta`
SET `meta_value` = TRIM(`meta_value`)
WHERE `meta_key` LIKE 'my_meta_key';
Your expression TRIM('meta_value') is trimming the string 'meta_value', not the value in the column.
Related
I am trying to replace some sentences from wordpress posts content using phpMyadmin
here is my update query
UPDATE `wp_posts` SET `post_content` = REPLACE (`post_content`, 'Example Routes:', 'Routes:') WHERE `post_content` LIKE '%Example Routes:%';
but it says "0 rows affected".
I have run a select query that have the same condition to ensure that there is resutls and I have so many resutls
here is the select query
SELECT * FROM `wp_posts` WHERE `post_content` LIKE '%Example Routes:%';
Please note that both query conditions is the same as what I am updating my condition is "LIKE '%Example Routes:%'" and the update is "REPLACE (post_content, 'Example Routes:', 'Routes:')".
Any idea why the update is giving me 0 rows affected?
Try dropping the space between REPLACE and the opening parenthesis:
UPDATE `wp_posts` SET `post_content` = REPLACE(`post_content`, 'Example Routes:', 'Routes:')
WHERE `post_content` LIKE '%Example Routes:%';
By default, you aren't allowed to include whitespace between function names and their parentheses: http://dev.mysql.com/doc/refman/5.7/en/functions.html
After a lot of search and working around I figured it out, the select query give results because the LIKE operator is not case sensitive but Replace is, so I needed to replace 'Example Routes:' to 'Example routes:' in the replace function which is a bit tricky.
I ended up using this query which works for me
UPDATE `wp_posts` SET `post_content` = REPLACE(`post_content`,'Example routes:','Routes:')
WHERE `post_content` LIKE '%Example Routes:%';
I am having a very annoying problem trying to import a wordpress db backup I am using wootickets to sell tickets for an event and for a customers db its complaing on xampp that their is a a illegal double here in the insert into statement shown below. Their hudreds of these values scattered thruought the the file i persume used for security.
INSERT INTO fl_postmeta ( meta_id , post_id , meta_key , meta_value ) VALUES ( 165743, 3313, '_tribe_wooticket_security_code', 'e801d16bb2' );
MySQL said: Documentation
1367 - Illegal double '342e880385' value found during parsing
My Question is why would this be the case when i exported from a linux platform to xamp for testing how do i fix this
The value 342e880385 should be put inside single quotes, like so:
INSERT INTO fl_postmeta ( meta_id , post_id , meta_key , meta_value )
VALUES ( 162936, 3115, '_tribe_wooticket_security_code', '342e880385' );
Otherwise, MySQL will try to parse it as a number.
I have just upgraded Magento from 1.5.1.0 to 1.9.2.1 and I am stuck at this error when I try to view a product:
a:5:{i:0;s:1427:"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'rule.calculate_subtotal' in 'field list', query was: SELECT `main_table`.`tax_calculation_rate_id`, `main_table`.`tax_calculation_rule_id`, `main_table`.`customer_tax_class_id`, `main_table`.`product_tax_class_id`, `rule`.`priority`, `rule`.`position`, `rule`.`calculate_subtotal`, `rate`.`rate` AS `value`, `rate`.`tax_country_id`, `rate`.`tax_region_id`, `rate`.`tax_postcode`, `rate`.`tax_calculation_rate_id`, `rate`.`code`, IF(title_table.value IS NULL, rate.code, title_table.value) AS `title` FROM `tax_calculation` AS `main_table` INNER JOIN `tax_calculation_rule` AS `rule` ON `rule`.`tax_calculation_rule_id` = main_table.tax_calculation_rule_id INNER JOIN `tax_calculation_rate` AS `rate` ON rate.tax_calculation_rate_id = main_table.tax_calculation_rate_id LEFT JOIN `tax_calculation_rate_title` AS `title_table` ON rate.tax_calculation_rate_id = title_table.tax_calculation_rate_id AND title_table.store_id = '1' WHERE (customer_tax_class_id = 3) AND (product_tax_class_id IN ('2')) AND (rate.tax_country_id = 'GB') AND (rate.tax_region_id IN(0, 0)) AND (rate.zip_is_range IS NULL) AND (rate.tax_postcode IS NULL OR rate.tax_postcode IN('*', '', 'ig9 5bw', 'ig9 5bw*', 'ig9 5b*', 'ig9 5*', 'ig9 *', 'ig9*', 'ig*', 'i*')) ORDER BY `priority` ASC, `tax_calculation_rule_id` ASC, `tax_country_id` DESC, `tax_region_id` DESC, `tax_postcode` DESC, `value` DESC";i:1;s:6703:"#0 /home/wwwarabesquecost/public_html/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
I have tried to manually add it using this link : https://sarfarazlaghari.wordpress.com/2015/06/06/magento-sqlstate42s22-column-not-found-1054-unknown-column-rule-calculate_subtotal-in-field-list/ but this doesn't make a difference.
Has anybody had this issue before?
Regarding
I have tried to manually add it using this link : https://sarfarazlaghari.wordpress.com/2015/06/06/magento-sqlstate42s22-column-not-found-1054-unknown-column-rule-calculate_subtotal-in-field-list/ but this doesn't make a difference
Are you saying you've added the column to the tax_calculation_rule table but you're still getting the above error? If that's the case then you've updated the wrong database table, or a configuration file in app/etc is pointed at a different database from the one you think it is.
If that's not what you're saying then be clearer in your question.
The query that you found at that link has an obvious error: it create a new field in the table with the same name of the table.
The right query, which solve the error, is the following:
ALTER TABLE tax_calculation_rule
ADD calculate_subtotal TINYINT(1) NOT NULL DEFAULT 0
Hope it helps.
You shouldn't run sql alternations just like that. The OP mentioned this has happened after an upgrade to 1.9x.
Having such errors means that your codebase is upgraded but your database is still outdated.
The best way for this would be to alter the core_resource table for the module (e.g. tax_setup) to the version that his database was aware previously, and let magento handle the database updates.
I'm having trouble with this snippet of code, and can't find any errors:
$query = "CREATE TABLE ? (? INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(?), ? VARCHAR(30), ? VARCHAR(50), ? TIMESTAMP, ? VARCHAR(50), ? DECIMAL(15, 2), ? DECIMAL(3, 2), ? VARCHAR(255))";
$array = array($table_name, $id, $id, $a_title, $c_title, $date_updated_title, $s_title, $ds_title, $ps_title, $u_title);
try {
$results = db_query($db, $query, $array); // db_query() is my PDO function to query the database. This function works fine elsewhere.
echo($table_name . " create successfully!");
} catch (PDOException $e) {
echo('<br />Could not create table "' . $table_name . '".');
return false;
error($e); //error() is my function to write errors to my log, and works fine elsewhere.
}
When I run this in my browser, it returns my caught exception 'Could not create table "name".' However, I don't see any error in my log, so I don't know if it's a syntax issue, or what.
When I take the query itself, and replace the question marks with the actual values, and dump it in PHPMyAdmin, it creates the table fine. I'm not really sure what the issue is here. I've had reasonable success with PDO on another site, but I'm still relatively new. Any ideas?
Thanks for the help!
[Edit] I've since tried using this query:
"CREATE TABLE $a_title (? INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(?), ? VARCHAR(30), ? VARCHAR(50), ? TIMESTAMP, ? VARCHAR(50), ? DECIMAL(15, 2), ? DECIMAL(3, 2), ? VARCHAR(255))";
I've tried with both single and double quotes. I also removed the $table_name variable from the array. Still getting a syntax error, and not sure why.
Comment from #DCoder is correct. You can use a query parameter only in place where you could normally put a single string literal, date literal, or numeric literal.
You can't use a query parameter for:
Table names
WRONG: SELECT * FROM ?
Column names
WRONG: SELECT * FROM table WHERE ? = 1234
Lists of values
WRONG: SELECT * FROM table WHERE column IN (?)
Though you could use IN() with a list of parameter placeholders, one for each scalar value.
SQL operators, expressions, or keywords
WRONG: SELECT * FROM table WHERE column ? 'value' AND ? ORDER BY column ?
For those cases, if you want dynamic content to become part of your query, the content must be part of the query before you call prepare().
But this means that you're back to interpolating variables into SQL query strings, which we are told is a no-no for its SQL injection risk.
The solution is to use filtering and whitelisting to make sure that the content doesn't contain some unsafe content. For example, if it's a dynamic table name, strip out anything but characters you know you want to keep, and then also delimit the table name just in case someone names their table a reserved word like "table" or "order" or something.
$table = preg_replace("/[^\w]/", "", $table);
$sql = "CREATE TABLE `{$table}` ( ... )";
Re your comment:
Yes, column names are off limits as well. As I said at the top, parameters are only for scalar values.
You also need to learn the appropriate usage of the three different types of quote marks.
What is the difference between single and double quotes in SQL?
Do different databases use different name quote?
What I've been trying to do is to select a row from a table while treating the varchar cells as int ones,
Here's a little explanation:
I have a table of phone numbers, some have "-" in them, some don't.
I wanted to select a number from the database, without including those "-" in the query.
So I used this preg_replace function:
$number = preg_replace("/[^0-9]/","",$number); //that leaves only the numbers in the variable
and then I run the following query:
"SELECT * FROM `contacts` WHERE `phone` = '{$number}'"
Now, of course it won't match sometimes since the number Im searching may have "-" in the database, so I tried to look for a solution,
on solution is just converting the cells into int's, but I'm not interested in doing that,
So after looking around, I found a MySQL function named CAST, used like : CAST(phone AS UNSIGNED)
I tried to mess with it, but it didn't seem to work.
Edit:
I kept looking around for a solution, and eventually used MySQL's REPLACE function for that.
"SELECT * FROM `contacts` WHERE REPLACE(phone,'-','') = '{$number}'"
Thank you all for your help.
MySQL doesn’t support extraction of regex matches.
You could try writing a stored function to handle it, but your best bet is to convert the data to ints so that all the numbers are uniform. I know you said you don't want to do that, but if you can, then it’s the best thing to do. Otherwise, you could do something like:
"SELECT * FROM `contacts` WHERE `phone` = '{$number}' OR `phone` = '{$number_with_dashes}'"
That is, search for the plain number OR the number with dashes.
1.
The easiest way to do it might be by using the REPLACE operator.
SELECT * FROM `contacts` WHERE REPLACE(REPLACE(`phone`, '-', ''), ' ', '') = '5550100';
What it does is simpy replacing all whitespaces and dashes with nothing, namely removing all spaces and dashes.
2.
Another alternative to solve the problem would be to use LIKE. If the phone numbers with a dash always are formatted the same way like 555-0100 and 555-0199 you can simple insert a %-sign instead of the dash. If your number may be formatted in different ways you can insert a %-between every character. It's not a beautiful solution but it does the trick.
SELECT * FROM `contacts` WHERE `phone` LIKE '555%0100';
or
SELECT * FROM `contacts` WHERE `phone` LIKE '5%5%5%0%1%0%0';
3.
You can use regular expressions. Since MySQL doesn't implement regex replace functions you need to use user defined functions. Have a look at https://launchpad.net/mysql-udf-regexp. It supports REGEXP_LIKE, REGEXP_SUBSTR, REGEXP_INSTR and REGEXP_REPLACE.
Edit: Removed my first answer and added some other alternatives.
I kept looking around for a solution, and eventually used MySQL's REPLACE function for that.
"SELECT * FROM `contacts` WHERE REPLACE(phone,'-','') = '{$number}'"