mysql query что возвращает
mysql_query
mysql_query — Посылает запрос MySQL
Описание
mysql_query() посылает запрос активной базе данных сервера, на который ссылается переданный указатель. Если параметр link_identifier опущен, используется последнее открытое соединение. Если открытые соединения отсутствуют, функция пытается соединиться с СУБД, аналогично функции mysql_connect() без параметров. Результат запроса буфферизируется.
Строка запроса НЕ должна заканчиваться точкой с запятой.
Только для запросов SELECT, SHOW, EXPLAIN, DESCRIBE, mysql_query() возвращает указатель на результат запроса, или FALSE если запрос не был выполнен. В остальных случаях, mysql_query() возвращает TRUE в случае успешного запроса и FALSE в случае ошибки. Значение не равное FALSE говорит о том, что запрос был выполнен успешно. Он не говорит о количестве затронутых или возвращённых рядов. Вполне возможна ситуация, когда успешный запрос не затронет ни одного ряда.
Следующий запрос составлен неправильно и mysql_query() вернёт FALSE:
Пример #1 Пример использования mysql_query()
Следующий запрос ошибочен, если колонки my_col нет в таблице my_tbl, в таком случае mysql_query() вернёт FALSE:
Пример #2 Пример использования mysql_query()
mysql_query() также считается ошибочным и вернёт FALSE, если у вас не хватает прав на работу с указанной в запросе таблицей.
mysqli::query
Описание
Выполняет запрос query к базе данных.
Список параметров
Предупреждение безопасности: SQL-инъекция
Режим результата может быть одной из 3 констант, указывающих, как результат будет возвращён сервером MySQL.
Возвращаемые значения
Примеры
Пример #1 Пример использования mysqli::query()
Результат выполнения данных примеров:
Смотрите также
User Contributed Notes 22 notes
This may or may not be obvious to people but perhaps it will help someone.
When running joins in SQL you may encounter a problem if you are trying to pull two columns with the same name. mysqli returns the last in the query when called by name. So to get what you need you can use an alias.
Below I am trying to join a user id with a user role. in the first table (tbl_usr), role is a number and in the second is a text name (tbl_memrole is a lookup table). If I call them both as role I get the text as it is the last «role» in the query. If I use an alias then I get both as desired as shown below.
= «SELECT a.uid, a.role AS roleid, b.role,
FROM tbl_usr a
INNER JOIN tbl_memrole b
ON a.role = b.id
» ;
?>
In this situation I guess I could have just renamed the role column in the first table roleid and that would have taken care of it, but it was a learning experience.
The cryptic «Couldn’t fetch mysqli» error message can mean any number of things, including:
When calling multiple stored procedures, you can run into the following error: «Commands out of sync; you can’t run this command now».
This can happen even when using the close() function on the result object between calls.
To fix the problem, remember to call the next_result() function on the mysqli object after each stored procedure call. See example below:
// Check for errors
if( mysqli_connect_errno ()) <
echo mysqli_connect_error ();
>
Here is an example of a clean query into a html table
I like to save the query itself in a log file, so that I don’t have to worry about whether the site is live.
For example, I might have a global function:
Translation:
«Couldn’t fetch mysqli»
You closed your connection and are trying to use it again.
It has taken me DAYS to figure out what this obscure error message means.
Use mysqli_query to call a stored procedure that returns a result set.
Here is a short example:
For those using with replication enabled on their servers, add a mysqli_select_db() statement before any data modification queries. MySQL replication does not handle statements with db.table the same and will not replicate to the slaves if a scheme is not selected before.
Building inserts can be annoying. This helper function inserts an array into a table, using the key names as column names:
Calling Stored Procedures
Beeners’ note/example will not work. Use mysqli_multi_query() to call a Stored Procedure. SP’s have a second result-set which contains the status: ‘OK’ or ‘ERR’. Using mysqli_query will not work, as there are multiple results.
mysqli::query() can only execute one SQL statement.
Use mysqli::multi_query() when you want to run multiple SQL statements within one query.
Use difference collation/character for connect, result.
You can set the collation before your query.
E.g. want to set the collation to utf8_general_ci
you can send the query «SET NAMES ‘utf8′» first
Also SET NAMES can repalce with one or some settings like SET character_set_results=’utf8′;
or you could just extend the class.
in my case i already had a wraper for the db so something like this was easy :
public function free($result) <
just tried it and it works like a charm 😉
Recently I had puzzling problem when performing DML queries, update in particular, each time a update query is called and then there are some more queries to follow this error will show on the page and go in the error_log:
«Fatal error: Exception thrown without a stack frame in Unknown on line 0»
The strange thing is that all queries go through just fine so it didn’t make much sense:
So, I don’t know why but it seems that when DML queries are responsible for:
«Fatal error: Exception thrown without a stack frame in Unknown on line 0»
calling «mysqli_free_result» after the query seems to be fixing the issue
mysql_query
mysql_query — Посылает запрос MySQL
Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:
Описание
Список параметров
Запрос не должен заканчиваться точкой с запятой. Данные в запросе должны быть корректно проэкранированы.
Возвращаемые значения
Для запросов SELECT, SHOW, DESCRIBE, EXPLAIN и других запросов, возвращающих результат из нескольких рядов, mysql_query() возвращает дескриптор результата запроса ( resource ), или false в случае возникновения ошибки.
Для других типов SQL-запросов, INSERT, UPDATE, DELETE, DROP и других, mysql_query() возвращает true в случае успешного выполнения и false в случае возникновения ошибки.
Полученный дескриптор результата нужно передать в функцию mysql_fetch_assoc() или любую другую функцию, работающую с результатами запросов.
Используйте mysql_num_rows() для выяснения количества рядов в результате SELECT-запроса или mysql_affected_rows() для выяснения количества обработанных рядов запросами DELETE, INSERT, REPLACE и UPDATE.
Примеры
Пример #1 Неверный запрос
Пример #2 Верный запрос
// Эти данные, к примеру, могли быть получены от пользователя
$firstname = ‘fred’ ;
$lastname = ‘fox’ ;
Смотрите также
User Contributed Notes 26 notes
Simulating an atomic operation for application locks using mysql.
$q = «update `table` set `LOCK`=’F’ where `ID`=’1′»;
$lock = mysql_affected_rows();
If we assume
NOT LOCKED = «» (empty string)
LOCKED = ‘F’
then if the column LOCK had a value other than F (normally should be an empty string) the update statement sets it to F and set the affected rows to 1. Which mean than we got the lock.
If affected rows return 0 then the value of that column was already F and somebody else has the lock.
The secret lies in the following statement taken from the mysql manual:
«If you set a column to the value it currently has, MySQL notices this and does not update it.»
Of course all this is possible if the all application processes agree on the locking algorithm.
mysql_query doesnt support multiple queries, a way round this is to use innodb and transactions
this db class/function will accept an array of arrays of querys, it will auto check every line for affected rows in db, if one is 0 it will rollback and return false, else it will commit and return true, the call to the function is simple and is easy to read etc
———-
function transaction($q_array) <
$retval = 1;
if($retval == 0) <
$this->rollback();
return false;
>else <
$this->commit();
return true;
>
>
/* Create database connection object */
$database = new MySQLDB;
// then from anywhere else simply put the transaction queries in an array or arrays like this:
$q = array (
array(«query» => «UPDATE table WHERE something = ‘something'»),
array(«query» => «UPDATE table WHERE something_else = ‘something_else'»),
array(«query» => «DELETE FROM table WHERE something_else2 = ‘something_else2′»),
);
Regarding the idea for returning all possible values of an enum field, the mySQL manual says that «SHOW COLUMNS FROM table LIKE column» should be used to do this.
The function below (presumes db connection) will return an array of the possible values of an enum.
function GetEnumValues($Table,$Column)
<
$dbSQL = «SHOW COLUMNS FROM «.$Table.» LIKE ‘».$Column.»‘»;
$dbQuery = mysql_query($dbSQL);
$EnumValues = substr($EnumValues, 6, strlen($EnumValues)-8);
$EnumValues = str_replace(«‘,'»,»,»,$EnumValues);
This is just a quick example to show how to do it, some tidying up needs to be done (ie checking if the field is actually an enum) before it is perfect.
This project implements a wrapper to mysql functions in PHP7.0+
tested and working fine =)
When trying to INSERT or UPDATE and trying to put a large amount of text or data (blob) into a mysql table you might run into problems.
In mysql.err you might see:
Packet too large (73904)
You would just replace maxsize with the max size you want to insert, the default is 65536
It should be noted that mysql_query can generate an E_WARNING (not documented). The warning that I hit was when the db user did not have permission to execute a UDF.
Expected behavior would be like an Invalid SQL statement, where there is no E_WARNING generated by mysql_query.
Warning: mysql_query() [function.mysql-query]: Unable to save result set in filename.php
The mysql_errno is 1370 and the mysql_error is:
execute command denied to user ‘username’@’%’ for routine ‘database_name.MyUDF’
If, like me, you come from perl, you may not like having to use sprintf to ‘simulate’ placeholders that the DBI package from perl provides. I have created the following wrapper function for mysql_query() that allows you to use ‘?’ characters to substitute values in your DB queries. Note that this is not how DBI in perl handles placeholders, but it’s pretty similar.
// oops, wrong userid or passwd
else <
echo «Invalid username and password combination.\n» ;
>
?>
When you run a select statement and receive a response, the data types of your response will be a string regardless of the data type of the column.
Use this to neatly insert data into a mysql table:
I believe there is a typo in celtic at raven-blue dot com version with:
I think you really ment:
Keep in mind when dealing with PHP & MySQL that sending a null-terminated string to a MySQL query can be misleading if you use echo($sql) in PHP because the null terminator may not be visible.
For example (this assumes connection is already made),
$string1 = «mystring\0»;
$string2 = «mystring»;
$query1 = «SELECT * FROM table WHERE mystring='».$string1.»‘»
$query2 = «SELECT * FROM table WHERE mystring='».$string2.»‘»
//but printing these queries to the screen will provide the same result
echo($result1);
echo($result2);
Not knowing this could lead to some mind-numbing troubleshooting when dealing with any strings with a null terminator. So now you know! 🙂
this could be a nice way to print values from 2 tables with a foreign key. i have not yet tested correctly but it should work fine.
Here’s a parameterised query function for MySQL similar to pg_query_params, I’ve been using something similar for a while now and while there is a slight drop in speed, it’s far better than making a mistake escaping the parameters of your query and allowing an SQL injection attack on your server.
# Parameterised query implementation for MySQL (similar PostgreSQL’s PHP function pg_query_params)
# Example: mysql_query_params( «SELECT * FROM my_table WHERE col1=$1 AND col2=$2», array( 42, «It’s ok» ) );
For all you programmers out there getting the ‘Command out of synch’ errors when executing a stored procedure call:
There are known bugs related to this issue, and the best workaround for avoiding this error seems to be switching to mysqli.
Still, I needed mysql to also handle these calls correctly.
The error is normally related to wrong function call sequences, though the bug report at http://bugs.php.net/bug.php?id=39727 shows otherwise.
For me, after commenting out hundreds of lines and several introspection calls to parse the procedure information (using information_schema and ‘SHOW’ extensions), I still got the same error.
The first result is returned, because I initiated my connection using the MYSQL_MULTI_RESULTS value of 131072 (forget this and you will never get any output, but an error message stating mysql cannot return results in this context)
After testing with this code (sproc2 simply calls ‘SELECT * FROM sometable’), I found the error must be in the mysql library/extension. Somehow, mysql does not handle multiple resultsets correctly, or is at least missing some functionality related to handling multiple results.
So if you ever make a uniform database accessing interface and implement stored procedures/prepared statements (or classes for it), this could be a solution if you really wish to enable stored procedures.
Still, be aware that this is really a serious flaw in your design (and IMHO, the mysql extension)
Also see the documentation for mysqli on mysqli_query, which seems to be working fine.
here’s a script for parsing a *.sql file (tested only on dumps created with phpMyAdmin) which is short and simple (why do people say «here’s a short and simple script» and it has a 100 lines?). the script skips comments and allows ; to be present within the querys
I much prefer to use the same syntax for single INSERT, REPLACE and UPDATE queries as it is easier to read and keeps my code shorter (no seperate building of insert and update values)
INSERT INTO table SET x=’1′, y=3
UPDATE table SET x=’2′ WHERE y=3
So if your using a function to build your query, you will only ever need to code the «field=value, field2=value2» part for any query.
/* malformed query /*
$rs = mysql_query(«SELECT `foo` FRO `bar`»);
if($rs) <
echo «This will never be echoed»;
>
?>
One way to reduce the dangers of queries like the dlete command above that dletes the whole DB is to use limits wherever possible.
EG. If you have a routine that is only deisnged to delete 1 record, add ‘LIMIT 1’ to the end of the command. This way you’ll only lose one record if someone does something stupid.
Just don’t trust ANY data that is sent to your script.
If you need to execute sevaral SQL commands in a row (usually called batcg SQL) using PHP you canot use mysql_query() since it can execute single command only.
Here is simple but effective function that can run batch SQL commands. Take cere, if string contains semicolon (;) anywhere except as command delimiter (within string expression for example) function will not work.
For those of you whom spent hours bashing your brains against the keyboard wondering why your non-English characters are output as question marks. Try the following:
?>
Simply run the query «set names ‘utf8’ » against the MySQL DB and your output should appear correct.
mysql_query — Посылает запрос MySQL
Данное расширение устарело, начиная с версии PHP 5.5.0, и будет удалено в будущем. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API и соответствующий FAQ для получения более подробной информации. Альтернативы для данной функции:
Описание
Список параметров
Запрос не должен заканчиваться точкой с запятой. Данные в запросе должны быть корректно проэкранированы.
Возвращаемые значения
Для запросов SELECT, SHOW, DESCRIBE, EXPLAIN и других запросов, возвращающих результат из нескольких рядов, mysql_query() возвращает дескриптор результата запроса ( resource ), или FALSE в случае ошибки.
Для других типов SQL-запросов, INSERT, UPDATE, DELETE, DROP и других, mysql_query() возвращает TRUE в случае успеха и FALSE в случае ошибки.
Полученный дескриптор результата нужно передать в функцию mysql_fetch_assoc() или любую другую функцию, работающую с результатами запросов.
Используйте mysql_num_rows() для выяснения количества рядов в результате SELECT-запроса или mysql_affected_rows() для выяснения количества обработанных рядов запросами DELETE, INSERT, REPLACE и UPDATE.
Примеры
Пример #1 Неверный запрос
Пример #2 Верный запрос
// Эти данные, к примеру, могли быть получены от пользователя
$firstname = ‘fred’ ;
$lastname = ‘fox’ ;
Смотрите также
Учебник по PHP 4
1 сайт | 36367 | 13.0% |
2-3 сайта | 19159 | 6.9% |
не больше 10 сайтов | 13841 | 5.0% |
10-20 сайтов | 11246 | 4.0% |
Так много, что не могу сосчитать | 143749 | 51.6% |
Я вообще не делаю сайты | 54365 | 19.5% |
Общее количество проголосовавших составляет: 278727
mysql_queryФункция mysql_query Посылает запрос MySQL mysql_query() посылает запрос активной базе данных сервера, на который ссылается переданный указатель. Если параметр link_identifier опущен, используется последнее открытое соединение. Если открытые соединения отсутствуют, функция пытается соединиться с СУБД, аналогично функции mysql_connect() без параметров. Результат запроса буфферизируется. Только для запросов SELECT, SHOW, EXPLAIN, DESCRIBE, mysql_query() возвращает указатель на результат запроса, или FALSE если запрос не был выполнен. В остальных случаях, mysql_query() возвращает TRUE в случае успешного запроса и FALSE в случае ошибки. Значение не равное FALSE говорит о том, что запрос был выполнен успешно. Он не говорит о количестве затронутых или возвращённых рядов. Вполне возможна ситуация, когда успешный запрос не затронет ни одного ряда. Следующий запрос составлен неправильно и mysql_query() вернёт FALSE: Следующий запрос ошибочен, если колонки my_col нет в таблице my_tbl, в таком случае mysql_query() вернёт FALSE: mysql_query() также считается ошибочным и вернёт FALSE, если у вас не хватает прав на работу с указанной в запросе таблицей. Работая с результатами запросов, вы можете использовать функцию mysql_num_rows(), чтобы найти число, возвращённых запросом SELECT, рядов, или mysql_affected_rows(), чтобы найти число рядов, обработанных запросами DELETE, INSERT, REPLACE, или UPDATE. Только для запросов SELECT, SHOW, DESCRIBE, EXPLAIN, функция mysql_query() возвращает указатель на результат, который можно использовать в функции mysql_fetch_array() и других функциях, работающих с результатами запросов. Когда работа с результатом окончена, вы можете освободить ресурсы, используемые для его хранения, с помощью функции mysql_free_result(), хотя память в любом случае будет очищена в конце исполнения скрипта. Если Вам нужна частная профессиональная консультация от авторов многих книг Кузнецова М.В. и Симдянова И.В., добро пожаловать в наш Консультационный Центр SoftTime.
|