use of period(.) while updating wamp password - mysql

While updating the WAMP password we use an UPDATE query:
update mysql.user set password = password('somepassword') where user = 'root';
Alternatively as explained here.
Here many feel we cannot use the dot(.) operator (mainly used in PHP) and use concat or + instead.
But in this UPDATE scenario—which I mentioned above—I was unable to use concat or + either.
So under what scnerio should we use . and + or in other words what is the main difference between . and + in mysql

The . in this:
mysql.user
Basically means to do something to the table user in the database mysql. In other words, mysql.user equates to [database].[table]. It is not concatenation but rather simply the way MySQL syntax works. Read more here.
The question you linked to was about using . to concatenate in PHP a value that would go into a MySQL query string. Completely different thing.

Related

C# MySql Syntax Exception when querying against an IP addres

I'm querying against an IP address stored in a table of a database with the following:
"SELECT user_id, is_login FROM users WHERE last_ip_address = '" + this.GetIPAddress() + "'"
I know that the IP is in the table because I see it there. I'm literally staring at it, but this query returns no rows.
When I run it without the single tick quotes ('), I get a syntax error:
"SELECT user_id, is_login FROM users WHERE last_ip_address = " + this.GetIPAddress()
So where is this going wrong? The IP returned by the function is the standard format ###.###.###.### IP address, and the syntax error itself is this:
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.##.#' at line 1"}
Edit: Some more info, the field itself is a varchar(30) type, and it says Collation = latin1_swedish_ci, but I don't even know what that is.
Thanks
Try using a LIKE then:
"SELECT user_id, is_login FROM users WHERE last_ip_address LIKE '%" + this.GetIPAddress() + "%'"
Edit: I would try to change that collation to UTF8.
Okay I am sorry for the confusion. I am very new to using MySql with C# and very VERY new (like I mean I just started today) with MySqlConnector.
To make a long answer short, I was trying to treat the table like, well, a table, and just read from it like a two dimensional array, when what I needed to be doing was using the MySqlDataReader. I found a good answer here:
How to read columns and rows with C#?
Thanks all for your help and advice.

Entity Framework : Set MySQL custom environment variables

I have an issue with Entity Framework 5.0. I'm working with Silverlight 5 and MySQL 5.6 too.
I need to set an environment MySQL variable before each connexion to the MySQL server.
E.g
SET #my_var = 'test';
Under Mysql I don't have any issues.
The following raises an EntityFrameworkException (syntax error near '#').
this.ObjectContext.CreateQuery<object>(" SET #my_var = 'test' ");
OR
this.ObjectContext.CreateQuery<object>(" CALL set_my_var('test') ");
This last method raises a MySQLException saying that a DataReader is already open and need to be closed.
this.ObjectContext.ExecuteStoreQuery<object>(" CALL set_my_var('test') ", null);
I also tried to set a MySQL system environment (no '#') with the same result every time.
Any help will be much appreciated !
Thank you.
I tried so many things that I misspelled my variable in my code.
So the following finaly worked : ctx.ExecuteStoreCommand("SET #my_var = 'test'");
I decided to leave the instruction in the method Initialize of my domain service. This method is inherited of the LinqToEntitiesDomainService class.
But you need to set Allow User Variables=True in your MySQL connection string
(ref : Is it possible to use a MySql User Defined Variable in a .NET MySqlCommand?)
You simply need to use a recent version of the MySQL Connector because older versions use the '#' mark to define SQL parameters so it could conflict with custom variables. Now it uses the '?' mark : http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html
My library was already up to date (6.6.5).
Thank you for the help !
Since your statement is not a query (i.e. does not return any result) you should use ExecuteStoreCommand. Something like this should work:
ctx.ExecuteStoreCommand("SET #my_var = 'test'")

Hashing an entire column using sha512

I have a table with three columns named: Question, Answer, Hashed. I want to update the Hashed column with the Answer column hashed using sha512.
I've tried to do the update directly from my MySql database using this syntax, but it didn't work:
UPDATE TableName
SET Hashed = SHA512(Answer)
WHERE Hashed IS NULL
I know the syntax is wrong but not sure why.
Thanks in advance for your help!
R
Give this a shot.
UPDATE TableName SET Hashed=SHA2(Answer, 512) WHERE Hashed IS NULL;
Note that this will only work with MySQL 5.5 onward. For versions before 5.5, you'll have to use application code to hash it (PHP to get all the rows, iterate through and hash $row['answer'] to SHA512, then run the UPDATE commands on each)
(Source: http://dev.mysql.com/doc/refman/5.5/en//encryption-functions.html#function_sha2)
I hope this is not too late. Even if, maybe someone else will find out this hint:
UPDATE TableName SET Hashed = ENCRYPT('Answer', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))) WHERE Hashed IS NULL;
What it does, it creates sha-512 hash, with it's schema: $6$ from string 'Answer'
If you are using debian, you may also use mkpasswd from package libstring-mkpasswd-perl to generate SHA-512 for you, and update as string.

Find and Replace text in the entire table using a MySQL query

Usually I use manual find to replace text in a MySQL database using phpMyAdmin. I'm tired of it now, how can I run a query to find and replace a text with new text in the entire table in phpMyAdmin?
Example: find keyword domain.example, replace with www.domain.example.
For a single table update
UPDATE `table_name`
SET `field_name` = replace(same_field_name, 'unwanted_text', 'wanted_text')
From multiple tables-
If you want to edit from all tables, best way is to take the dump and then find/replace and upload it back.
The easiest way I have found is to dump the database to a text file, run a sed command to do the replace, and reload the database back into MySQL.
All commands below are bash on Linux.
Dump database to text file
mysqldump -u user -p databasename > ./db.sql
Run sed command to find/replace target string
sed -i 's/oldString/newString/g' ./db.sql
Reload the database into MySQL
mysql -u user -p databasename < ./db.sql
Easy peasy.
Running an SQL query in phpMyAdmin to find and replace text in all WordPress blog posts, such as finding mysite.example/wordpress and replacing that with mysite.example/news
Table in this example is tj_posts
UPDATE `tj_posts`
SET `post_content` = replace(post_content, 'mysite.example/wordpress', 'mysite.example/news')
Put this in a php file and run it and it should do what you want it to do.
// Connect to your MySQL database.
$hostname = "localhost";
$username = "db_username";
$password = "db_password";
$database = "db_name";
mysql_connect($hostname, $username, $password);
// The find and replace strings.
$find = "find_this_text";
$replace = "replace_with_this_text";
$loop = mysql_query("
SELECT
concat('UPDATE ',table_schema,'.',table_name, ' SET ',column_name, '=replace(',column_name,', ''{$find}'', ''{$replace}'');') AS s
FROM
information_schema.columns
WHERE
table_schema = '{$database}'")
or die ('Cant loop through dbfields: ' . mysql_error());
while ($query = mysql_fetch_assoc($loop))
{
mysql_query($query['s']);
}
phpMyAdmin includes a neat find-and-replace tool.
Select the table, then hit Search > Find and replace
This query took about a minute and successfully replaced several thousand instances of oldurl.ext with the newurl.ext within Column post_content
Best thing about this method : You get to check every match before committing.
N.B. I am using phpMyAdmin 4.9.0.1
Another option is to generate the statements for each column in the database:
SELECT CONCAT(
'update ', table_name ,
' set ', column_name, ' = replace(', column_name,', ''www.oldDomain.example'', ''www.newDomain.example'');'
) AS statement
FROM information_schema.columns
WHERE table_schema = 'mySchema' AND table_name LIKE 'yourPrefix_%';
This should generate a list of update statements that you can then execute.
UPDATE table SET field = replace(field, text_needs_to_be_replaced, text_required);
Like for example, if I want to replace all occurrences of John by Mark I will use below,
UPDATE student SET student_name = replace(student_name, 'John', 'Mark');
If you are positive that none of the fields to be updated are serialized, the solutions above will work well.
However, if any of the fields that need updating contain serialized data, an SQL Query or a simple search/replace on a dump file, will break serialization (unless the replaced string has exactly the same number of characters as the searched string).
To be sure, a "serialized" field looks like this:
a:1:{s:13:"administrator";b:1;}
The number of characters in the relevant data is encoded as part of the data.
Serialization is a way to convert "objects" into a format easily stored in a database, or to easily transport object data between different languages.
Here is an explanation of different methods used to serialize object data, and why you might want to do so, and here is a WordPress-centric post: Serialized Data, What Does That Mean And Why is it so Important? in plain language.
It would be amazing if MySQL had some built in tool to handle serialized data automatically, but it does not, and since there are different serialization formats, it would not even make sense for it to do so.
wp-cli
Some of the answers above seemed specific to WordPress databases, which serializes much of its data. WordPress offers a command line tool, wp search-replace, that does handle serialization.
A basic command would be:
wp search-replace 'an-old-string' 'a-new-string' --dry-run
However, WordPress emphasizes that the guid should never be changed, so it recommends skipping that column.
It also suggests that often times you'll want to skip the wp_users table.
Here's what that would look like:
wp search-replace 'https://old-domain.example' 'https://shiney-new-domain.com' --skip-columns=guid --skip-tables=wp_users --dry-run
Note: I added the --dry-run flag so a copy-paste won't automatically ruin anyone's database. After you're sure the script does what you want, run it again without that flag.
Plugins
If you are using WordPress, there are also many free and commercial plugins available that offer a gui interface to do the same, packaged with many additional features.
Interconnect/it PHP script
Interconnect/it offers a PHP script to handle serialized data: Safe Search and Replace tool. It was created for use on WordPress sites, but it looks like it can be used on any database serialized by PHP.
Many companies, including WordPress itself, recommends this tool. Instructions here, about 3/4 down the page.
UPDATE `MySQL_Table`
SET `MySQL_Table_Column` = REPLACE(`MySQL_Table_Column`, 'oldString', 'newString')
WHERE `MySQL_Table_Column` LIKE 'oldString%';
I believe "swapnesh" answer to be the best ! Unfortunately I couldn't execute it in phpMyAdmin (4.5.0.2) who although illogical (and tried several things) it kept saying that a new statement was found and that no delimiter was found…
Thus I came with the following solution that might be usefull if you exeprience the same issue and have no other access to the database than PMA…
UPDATE `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid`
FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
SET `toUpdate`.`guid`=`updated`.`guid`
WHERE `toUpdate`.`ID`=`updated`.`ID`;
To test the expected result you may want to use :
SELECT `toUpdate`.`guid` AS `old guid`,`updated`.`guid` AS `new guid`
FROM `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid`
FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
WHERE `toUpdate`.`ID`=`updated`.`ID`;
the best you export it as sql file and open it with editor such as visual studio code and find and repalace your words.
i replace in 1 gig file sql in 1 minutes for 16 word that total is 14600 word.
its the best way.
and after replace it save and import it again.
do not forget compress it with zip for import.
In the case of sentences with uppercase - lowercase letters,
We can use BINARY REPACE
UPDATE `table_1` SET `field_1` = BINARY REPLACE(`field_1`, 'find_string', 'replace_string')
Here's an example of how to find and replace in Database
UPDATE TABLE_NAME
SET COLUMN = replace(COLUMN,'domain.example', 'www.domain.example')
TABLE_NAME => Change it with your table name
COLUMN => Change it to your column make sure it exists
I have good luck with this query when doing a search and replace in phpmyadmin:
UPDATE tableName SET fieldName1 = 'foo' WHERE fieldName1 = 'bar';
Of course this only applies to one table at a time.
Generate change SQL queries (FAST)
mysql -e "SELECT CONCAT( 'update ', table_name , ' set ', column_name, ' = replace(', column_name,', ''www.oldsite.example'', ''www.newsite.example'');' ) AS statement FROM information_schema.columns WHERE table_name LIKE 'wp_%'" -u root -p your_db_name_here > upgrade_script.sql
Remove any garbage at the start of the file. I had some.
nano upgrade_script.sql
Run generated script with --force options to skip errors. (SLOW - grab a coffee if big DB)
mysql -u root -p your_db_name_here --force < upgrade_script.sql

problem with mysql query when password like \/'

In mysql table name (user_login) and i having field like login_name and password . I entered in login_name as abc and password as /'(Special symbols like \ / ') .And my query is
select password from user_login where password like '/'' and
I got sql syntax error
You should use parameterised queries in what ever language you are implementing the call in. Beware SQL Injection attack
you should use parameters instead of putting varibles directly into the query. i think it's aproblem with the escaping symbol.
check out this link How to set query parameters in MySQL Query Browser?
If you ever use LIKE in a login system you have thrown ALL SECURITY OUT THE WINDOW. Try this on your login to see what I mean:
Username: %
Password: %
ACCESS GRANTED FOR FIRST USER IN DATABASE. ( pray that isn't an admin user )
If the username is known then % as a password will give full access.
If you want a friendlier system that is not case sensitive ( yes this reduces the possible number of passwords - but is likely appropriate for usernames ) then force the case to lower ( or upper or ucwords or whatever you prefer ) - but DO NOT use the LIKE operator in ANY QUERY involving a login or unscreened user input ( such as search boxes ). Anytime you must use the LIKE operator BE SURE TO STRIP OUT OR MANUALLY ESCAPE % and _ (and if you're using MS SQL then escape all the REGEX operators too - []^$()*. ).
A lot of escaping functions for mysql will not escape the % _ characters, which - when used with LIKE - allows any visitor the ability to do wildcard searches ( can severely bog down the server and cause DoS issues ) and worse grant themselves undue privileges using %:% to login.