Should I try to rid my MySQL database of back-slashes? - mysql

I'm using PDO prepared statements to insert data into a MySQL database, and I notice that apostrophes (single quotes) in strings are being stored in the database with back-slashes (\) preceding them.
I use stripslashes($string) on output, and of course this gets rid of them.
I searched my server's phpinfo() information (PHP version 5.2.17) for "magic_quotes" and found:
magic_quotes_gpc: local value = on, master value = on
magic_quotes_runtime: local value = off, master value = off
magic_quotes_sybase: local value = off, master value = off
Firstly, would turning magic_quotes_gpc off prevent the occurrence of the back-slashes? I don't currently have access to the server php.ini master settings, but as I understand it I would be able to disable it by configuring the root .htaccess file with the directive php_flag magic_quotes_gpc Off.
Secondly, is the prevention of these back-slashes in the database desirable? I ask this because I saw the somewhat cryptic remark here to "think twice before you do".

would turning magic_quotes_gpc off prevent the occurrence of the back-slashes?
Probably yes.
is the prevention of these back-slashes in the database desirable?
Yes. They serve no purpose. If you use PDO and properly parametrized queries, the problem that magic quotes used to address is already solved.
See the PHP manual on magic quotes on why they were used, and why they should no longer be used.

Related

How to resolve SQL table with prefix in PhpStorm?

I'm working on PhpStorm to develop my Prestashop websites and I can't resolve this issue. I work on localhost and successfully connected PhpStorm to my MySQL Server.
Now PhpStorm throws warnings like "unable to resolve table '${_DB_PREFIX_}cms'". Prestashop uses prefixes for table names and it seems PhpStorm can't resolve those tables with prefixes.
Is there a workaround for this ?
Here is a code exemple from Prestashop-1.6 sources :
$sql = 'SELECT c.`id_cms`, cl.`meta_title`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms` c
INNER JOIN `'._DB_PREFIX_.'cms_shop` cs
ON (c.`id_cms` = cs.`id_cms`)
INNER JOIN `'._DB_PREFIX_.'cms_lang` cl
ON (c.`id_cms` = cl.`id_cms`)
WHERE c.`id_cms_category` = '.(int)$id_cms_category.'
AND cs.`id_shop` = '.(int)$id_shop.'
AND cl.`id_lang` = '.(int)$id_lang.
$where_shop.'
AND c.`active` = 1
ORDER BY `position`';
The reason why this isn't work is because you are most likely only loading one schema, you need to load the information_schema.*
To do this, go to the database tab in the top right and where you have added your MySQL database right click and select properties.
Now you'll have a screen called Data Sources and Drivers, it should open on a tab called General, click the third tab called Schemas and and add information_schema.* to this list of loaded Schemas.
Click apply and okay and then PhpStorm will now know your database structure and then be intelligently able to work with you, therefor removing all the errors.
Edit: As mentioned here, this has been fixed in PhpStorm 2018.2, but only for constants.
I have a solution that doesn't involve throwing your IDE away. :)
However, a word of caution: it's an ugly hackā„¢ that comes without guarantees.
Assuming you already have a connection to the db in PhpStorm, generate the ddl for the desired db (Right Click on the connection -> SQL Scripts -> Generate DDL to Clipboard):
Paste the content into some sql file somewhere inside your project. You should probably gitignore this file.
Replace all the tables' prefix in this ddl file with the one from your code. Use the PhpStorm typehint as a guideline. For example '._DB_PREFIX_.'cms would become ${_DB_PREFIX_}cms:
Note that you may have to use backticks to avoid breaking sql syntax due to curly brackets.
Add the ddl to your phpstorm project:
Everything should now work:
Add this comment above the $sql query.
/** #noinspection SqlResolve */
This will suppress the warning only for this statement.
For future readers, this is now supported:
https://www.jetbrains.com/help/phpstorm/2021.1/ide-advanced-metadata.html#set-up-dynamic-prefixes-for-table-names-in-sql-language-injections
.phpstorm.meta.php
<?php
namespace PHPSTORM_META {
override(
// Virtual function to indicate that all SQL
// injections will have the following replacement rules.
sql_injection_subst(),
map([
'{' => "", // all `{` in injected SQL strings will be replaced with a prefix
'}' => '', // all `}` will be replaced with an empty string
]));
}
Edit: At time of writing (2016) there was no solution to this issue. But since 2018, as mentioned in Christian's answer, you can now use constants in SQL queries.
Actually there is no way to handle that. But you may disable inspection for such warning.
Open File > Settings > Editor > Inspections
Expand SQL
Uncheck Unresolved reference

Mysql SQL to update URLs that do not have www

I have a million odd rows where most start
'http://www.' or 'https://www.'
but occasionally they start with no 'www.' - this may be correct but the website owner wants consistency throughout the data and thus I need to update the table to always have 'www.'
I'm struggling with the SQL to do this. I tried:
select * from the_million where URL like 'http://[!w]'
But that returns 0 records so I've fallen at the first hurdle of building up the SQL. I guess after I've got the records I want I'll then do a replace.
I'm happy to run this in two goes for each of http and https so no need for anything fancy there.
You can try this query:
UPDATE the_million SET url=REPLACE(url, 'http://', 'http://www.')
WHERE url NOT LIKE 'http://www.%' AND url NOT LIKE 'https://www.%'
UPDATE the_million SET url=REPLACE(url, 'https://', 'https://www.')
WHERE url NOT LIKE 'http://www.%' AND url NOT LIKE 'https://www.%'
Search & replace in 2 queries.
try this
select * from the_million where URL not like 'http://www.%'
This condition:
URL like 'http://[!w]'
... is identical to this one:
URL='http://[!w]'
because it doesn't contain any valid wildcard for MySQL LIKE operator. If you check the MySQL manual page you'll see that the only wildcards are % and _.
The W3Schools page where you read that [!charlist] is valid identifies the section as "SQL Wildcards" which is misleading or plain wrong (depending on how benevolent you feel). That's not standard SQL at all. The error messages returned by their "SQL Tryit Editor" suggest that queries run against a Microsoft Access database, thus it's only a (pretty irrelevant) SQL dialect.
My advice:
Avoid W3Schools as reference site. Their info is often wrong and they apparently don't care enough to amend it.
Always use the official manual of whatever DBMS engine you are using.
Last but not least, the good old www prefix is not a standard part of the HTTP protocol URIs (like http://); it's only a naming convention. Preppending it to an arbitrary list of URLs is like adding "1st floor" to all your customer addresses. Make sure your client knows that he's paying money to corrupt his data on purpose. And if he feels generous, you can propose him to replace all https: with http: as well.

How to undo sql USE?

What's the SQL command to undo:
USE db;
The syntax I see everywhere is:
USE [db] ;
implying that I can leave out the db part. Not so - this is a syntax error however (maybe just syntax errors in the SQL syntax syntax?).
edit
The programming problem this is causing is that I can't reset the environment in which subsequent commands run. I could reset my DB connection, but this seems efficient.
cmdX; // Works
vs.
cmdX;
cmdY; // May fail because command X upset some state.
cmdX should clean up after itself and put things back where it found them.
Analogously:
cd ./a
doX()
cd ../
doY() // Y expects to not be in a?
I don't think you can. The documentation doesn't say the parameter is optional. It says:
The database remains the default until the end of the session or another USE statement is issued:
So if you want to drop the default, end your session and start a new one without selecting a DB.
What programming problem is this causing for you?
The database argument is not optional.
mysql> use
ERROR:
USE must be followed by a database name
I'm not sure where you saw this command with square brackets around the argument. That is not shown at the documentation page: http://dev.mysql.com/doc/refman/5.6/en/use.html
Microsoft SQL Server uses square brackets around identifiers (as opposed to a style to indicate an optional argument), but the MS SQL documentation for USE also doesn't show it: http://msdn.microsoft.com/en-us/library/ms188366.aspx
What would it mean to "undo" a USE command? Would it be like cd - in bash, making the previous default database again the default? There is no such command in MySQL for this. It doesn't remember what was your previous default database. If you want to return, you just have to USE that database and name it explicitly.

MySQL: CONCAT_WS function is running on local but not on server

Some days ago I asked a question about my problem and I was advised to use CONCAT_WS function. I am using CONCAT_WS on my local mysql database and it is working perfectly. But it is not working on server(application hosted) and generate the following error.
FUNCTION test.CONCAT_WS does not exist
Here test in error string is my database name on server.
My query is like this:
SELECT * FROM patient WHERE CONCAT_WS (',', LastName,FirstName,BirthDate ) NOT IN ('Abdul,Quddus,2000-09-30','Wasim,Akram,1993-09-12');
Can someone tell me the problem or suggest me another solution asked in linked question above ?
Thanks
The easiest way to fix it is by removing the whitespace between the function name and the parenthesis, i.e. CONCAT_WS(...) instead of CONCAT_WS (...).
From the MySQL Manual:
By default, there must be no
whitespace between a function name and
the parenthesis following it. This
helps the MySQL parser distinguish
between function calls and references
to tables or columns that happen to
have the same name as a function.
...
You can tell the MySQL server to
accept spaces after function names by
starting it with the
--sql-mode=IGNORE_SPACE option.
Also, this behavior depends on the MySQL version, this is why it works on one server and doesn't work on another, quote from the "Function Name Parsing and Resolution" manual page:
The number of function names affected
by IGNORE_SPACE was reduced
significantly in MySQL 5.1.13, from
about 200 to about 30.

Could not find server 'dbo' in sys.servers

I have a lot of services which query the database. All of them work fine but one service calling a stored procedure gives me following error:
Could not find server 'dbo' in
sys.servers. Verify that the correct
server name was specified. If
necessary, execute the stored
procedure sp_addlinkedserver to add
the server to sys.servers.
I have not idea why all the other stored procedures work fine and this one not...
By the way, I use SubSonic as data access layer.
Please run select name from sys.servers from the server which you mentioned as default server in configuration file.
Here in name column values should match with your server names used in the report query.
e.g serverXXX.databasename.schema.tablename
serverXXX should be there in the result of select name from sys.servers otherwise it gives error as got.
It sounds like there is an extra "." (or two) in the mapping - i.e. it is trying to find server.database.schema.object. Check your mapping for stray dots / dubious entries.
Also make sure that the server name matches what you think it is. If you rename the host that SQL Server is running on, you need to rename the SQL Server, too.
http://www.techrepublic.com/blog/datacenter/changing-the-name-of-your-sql-server/192
I had another issue with the same exception so I'll post here if someone stumble upon it:
Be careful if you specify the server name in synonyms. I had a different server name on my staging machine and production and it caused the same 'cannot find server'-error.
(Guess you shouldn't use synonyms that much anyway but it's useful in some migration scenarios)
In my case i was facing same issue with following ,
SqlCommand command = new SqlCommand("uspx_GetTemplate", connection);
but after adding square bracket to stored procedure name it get solved.
SqlCommand command = new SqlCommand("[uspx_GetTemplate]", connection);