Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Выглядит странно, что в 2012 году люди до сих пор открывают новое соединение каждый раз когда надо соединиться с базой.
Server:Apache/1.3.41 (Unix) mod_deflate/1.0.21 PHP/5.2.9
идея изначально противоречит идеологии постоянных соединений — «persistent connection служит только для экономии на коннекте, во всех остальных аспектах предоставляя клиенту абсолютно чистое соединение, во всём аналогичное новому»
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use ( mysql_close() will not close links established by mysql_pconnect()).
As there is some overhead associated with the COM_CHANGE_USER call, it is possible to switch this off at compile time. Reusing a persistent connection will then generate a COM_PING (mysql_ping) call to simply test the connection is reusable.
EXECUTE stmt2 USING @a, @b
CALL sp_takes_string_returns_string(?)
SELECT *
FROM `foo`
WHERE
`id` = :id AND
`status` = 'active'
$_GET['id'] = "1; DROP TABLE users";
поможет вам mysql_escape_string от этой (и любой другой) инъекции?поможет вам mysql_escape_string от этой (и любой другой) инъекции?
$query = 'SELECT * FROM `a` WHERE `id` = :id';
$query = str_replace(':id', '1; DROP', $query);
SELECT * FROM table WHERE id >? LIMIT?
Из мануала:
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?"); $stmt->execute(array("%$_GET[name]%")); $data = $stmt->fetchAll();
Ни «внешние», ни «все», ни «параметры» не имеют к функции mysql_escape_string ни малейшего отношения. У неё очень узкая область применения, не имеющая никакого отношения к защите от инъекций.
This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.
This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set.
:id либо подготавливается, либо экранируется. Одно из двух. Но не одновременно.
да, признаю: эскейпить все входящие параметры — дурацкая идея, с безопасностью ничего общая не имеющая:)
So why did this feature exist? Simple, to help prevent SQL Injection. Today developers are better aware of security and end up using database specific escaping mechanisms and/or prepared statements instead of relying upon features like magical quotes.
$sql .= " WHERE id = " . $id;
$id должно или приводиться к целому, или экранироваться и квотироваться, то есть или $sql .= " WHERE id = " . (int)$id;
или $sql .= " WHERE id = '" . mysql_real_escape_string($id) . "'";
, даже если строчкой выше идёт строка $id = 1;Queries must be absolutely the same. As no parsing is done before lookup queries are not normalized (would require parsing) before cache lookup, so they have to match byte by byte for cache hit to happen. This means if you would place dynamic comments in the query, have extra space or use different case – these would be different queries for query cache.
… при получении запроса MySQL определяет, равны ли первые три символа запроса «SEL». Отсюда следуют два важных правила: 1) MySQL выполняет побайтовое сравнение, поэтому запросы, имеющие отличие хотя бы в одном символе будут рассматриваться как два разных запроса.
Queries must be exactly the same (byte for byte) to be seen as identical.
MySQL attempts to locate the results of any SELECT query in the query cache before bothering to analyze or execute it. It does this by hashing the query and using the hashed value to check for the results in the cache. MySQL uses the exact query text it receives, so the cache is sensitive to the most trivial variations.
As far as the cache is concerned, the query:
SELECT * FROM table1
is different from:
select * FROM table1
Отчёт о попытке получить заявленную эффективность от prepared statements