mysql php mysql num rows php

mysqli_stmt::$num_rows

mysqli_stmt_num_rows

Описание

Возвращает количество строк, помещённых в буфер в выражении. Функция будет работать только после вызова mysqli_stmt_store_result() для буферизации всего набора результатов в дескрипторе оператора.

Список параметров

Возвращаемые значения

Целое число ( int ), представляющее количество буферизованных строк. Возвращает 0 в небуферизованном режиме, если с сервера не были получены все строки.

Примеры

Пример #1 Объектно-ориентированный стиль

Пример #2 Процедурный стиль

Результат выполнения данных примеров:

Смотрите также

User Contributed Notes 1 note

Please be advised, for people who sometimes miss to read this important Manual entry for this function:

If you do not use mysqli_stmt_store_result( ), and immediatley call this function after executing a prepared statement, this function will usually return 0 as it has no way to know how many rows are in the result set as the result set is not saved in memory yet.

mysqli_stmt_store_result( ) saves the result set in memory thus you can immedietly use this function after you both execute the statement AND save the result set.

If you do not save the result set but still want to use this function you have to actually loop through the result set one row at a time using mysqli_stmt_fetch( ) before using this function to determine the number of rows.

A thought though, if you want to determine the number of rows without storing the result set and after looping through it, why not just simply keep an internal counter in your loop every time a row is fetched and save the function call.

In short, this function is only really useful if you save the result set and want to determine the number of rows before looping through it, otherwise you can pretty much recreate its use like I suggested.

Источник

mysql_num_rows

mysql_num_rows — Возвращает количество рядов результата запроса

Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:

Описание

Список параметров

Возвращаемые значения

Количество рядов в результате запроса в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования mysql_num_rows()

Примечания

При использовании mysql_unbuffered_query() функция mysql_num_rows() не вернёт корректного значения до тех пор, пока все ряды не будут получены.

Для обратной совместимости может быть использован следующий устаревший псевдоним: mysql_numrows()

Смотрите также

User Contributed Notes 22 notes

Some user comments on this page, and some resources including the FAQ at :

This is not a particularly universal solution, and those who read these comments on this page should also be aware that

select count(*) may not give correct results if you are using «group by» or «having» in your query, as count(*) is an agregate function and resets eachtime a group-by column changes.

can be an alternative to sub-selects in mysql 3, and such queries cannot have the select fields replaced by count(*) to give good results, it just doesn’t work.

*Early detection of invalid constant expressions. MySQL quickly detects that some SELECT statements are impossible and returns no rows.

*All constant tables are read first, before any other tables in the query. A constant table is:
1) An empty table or a table with 1 row.
2) A table that is used with a WHERE clause on a UNIQUE index, or a PRIMARY KEY, where all index parts are used with constant expressions and the index parts are defined as NOT NULL.

Hopefully this will keep someone from staying up all night with 1146 errors, unless I am completely mistaken in thinking I have this figured out.

This seems the best workaround to get an ‘ordinary’ loop going, with possibility of altering output according to row number
(eg laying out a schedule)

In response to oran at trifeed dot com:

You are only experiencing this behaviour because you have not given your FOUND_ROWS() result an alias:

SELECT SQL_CALC_FOUND_ROWS together with
SELECT FOUND_ROWS()

After all there is an array of row arrays, as signified by
mysql_num_rows($result):

Say this gives «40 rows» : it would be useful to know when the iteration is on row 39.

The nearest seems to be «data seek»:but it connects directly to a
row number eg (from mysql_data_seek page)

= it still wouldn’t solve knowing what row number you’re on in an ordinary loop.

One reason for this situation is the php fetch (fetch-a-single-row) construction, without any reasonable FOR loop possibility with row numbers.

Suggestion:
$Rows[$i] possibility where
$i would be the row number

A note on the following usage; that suggest to use several MySQL Functions to get the number of Table Records.

You may be familiar with following:

= ‘Select SQL_CALC_FOUND_ROWS `MyField` From `MyTable` Limit 1;’ ;

$sqlQuery_1 = ‘Select FOUND_ROWS( );’ ;

?>

I omitted the actual connection to MySQL and the execution of the query, but you get the idea.

I did some tests and on a fairly high traffic web site, one that executes several queries quite often and found that using this combination of MySQL Functions can actually result in wrong results.

For example, assume I have two queries to get the number of Table Records in two different Tables. So in essence, we are executing 4 queries ( 2 queries for each Table ).

If two different requests come in through PHP, your going to run into problems. Note than when I mean request, I mean two different clients requesting your PHP page.

Execute: SQL_CALC_FOUND_ROWS On Table 1

Execute: SQL_CALC_FOUND_ROWS On Table 2

Execute: Select FOUND_ROWS( )

At this point, you see the race condition that occurred. While Request 1 was being executed, Request 2 came in.

At this point Request 1 will return the number of Table Records in Table 2 and not Table 1 as expected!

Why? Because MySQL does not differ between requests. Each query is in a queue waiting its turn. As soon as its turn comes in it will be executed my MySQL.

The MySQL Function Select FOUND_ROWS( ) will return the result of the last SQL_CALC_FOUND_ROWS!

MySQL 4.0 supports a fabulous new feature that allows you to get the number of rows that would have been returned if the query did not have a LIMIT clause. To use it, you need to add SQL_CALC_FOUND_ROWS to the query, e.g.

$sql = «Select SQL_CALC_FOUND_ROWS * from table where state=’CA’ limit 50»;
$result = mysql_query($sql);

$sql = «Select FOUND_ROWS()»;
$count_result = mysql_query($sql);

You now have the total number of rows in table that match the criteria. This is great for knowing the total number of records when browsing through a list.

To use SQL COUNT function, without select the source.

In preventing the race condition for the SQL_CALC_FOUND_ROWS and FOUND_ROWS() operations, it can become complicated and somewhat kludgy to include the FOUND_ROWS() result in the actual result set, especially for complex queries and/or result ordering. The query gets more complex, you may have trouble isolating/excluding the FOUND_ROWS() result, and mysql_num_rows() will return the number of actual results + 1, all of which makes your code messier and harder to read. However, the race condition is real and must be dealt with.

A alternative and cleaner method is to explicitly lock the table using a WRITE lock (preventing other processes from reading/writing to the table). The downsides I can see are a performance hit, and your mysql user must have lock permissions.

// excuse the use of mysqli instead of mysql

Actually I am a little ashamed to be saying this, but I stand corrected about a rather old note I posted on 17-Jul-2007 06:44.

Using SQL_CALC_FOUND_ROWS and FOUND_ROWS( ) will NOT trigger a race condition on MySQL, as that would pretty much defy their entire purpose.

The results for their usage is actually unique per connection session as it is impossible for processes to share anything in PHP. As far as PHP is concerned, each request represents a new connection to MySQL as each request is isolated to its own process.

To simulate this, create the following script:

?>

Set the connection and query information for something that matches your environment.

Run the script once with the Sleep query string and once again without it. Its important to run them both at the same time. Use Apache ab or something similar, or even easier, just open two browser tabs. For example:

If a race condition existed, the results of the first instance of the script would equal the results of the second instance of the script.

For example, the second instance of the script will execute the following SQL query:

( «SELECT SQL_CALC_FOUND_ROWS `aid` From `access` Limit 1» );

?>

This happens while the first instance of the script is sleeping. If a race condition existed, when the first instance of the script wakes up, the result of the FOUND_ROWS( ) it executes should be the number of rows in the SQL query the second instance of the script executed.

But when you run them, this is not the case. The first instance of the script returns the number of rows of its OWN query, which is:

( «SELECT SQL_CALC_FOUND_ROWS `bid` From `blocks` Limit 1» );

?>

So it turns out NO race condition exists, and every solution presented to combat this «issue» are pretty much not needed.

Источник

Ошибка с функцией mysqli_num_rows

Приветствую!
Никак не могу разобраться, почему выскакивает ошибка при попытке посчитать кол-во строк в массиве с помощью функции mysqli_num_rows?
Ошибка следующая:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/dyakovmi/domains/obninsk-enterprise.org/public_html/register2.php on line 30

Помощь в написании контрольных, курсовых и дипломных работ здесь.

mysql php mysql num rows php. Смотреть фото mysql php mysql num rows php. Смотреть картинку mysql php mysql num rows php. Картинка про mysql php mysql num rows php. Фото mysql php mysql num rows phpОшибка: mysqli_num_rows() expects parameter 1 to be mysqli_result
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in.

При вводе слова на русском, выдается ошибка «mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given»
Здравствуйте, у меня есть код поиска по данным таблицы из бд. Но когда я пытаюсь ввести слова на.

ошибка mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in
Мне нужно, чтобы данные с базы данных, а именно «$br» (данное поле принимает цифры на выбор.

Результат:В выборке 0 рядов.

Добавлено через 2 часа 12 минут
Здрузья! Молю о помощи!

Помощь в написании контрольных, курсовых и дипломных работ здесь.

mysql php mysql num rows php. Смотреть фото mysql php mysql num rows php. Смотреть картинку mysql php mysql num rows php. Картинка про mysql php mysql num rows php. Фото mysql php mysql num rows phpОшибки параметров mysqli_query и mysqli_num_rows
Доброго времени суток. Пишу систему регистрации и авторизации пользователей. При запросе данных из.

Источник

MySQLi раскладываем все по полочкам

mysql php mysql num rows php. Смотреть фото mysql php mysql num rows php. Смотреть картинку mysql php mysql num rows php. Картинка про mysql php mysql num rows php. Фото mysql php mysql num rows php
Для кого это статья? Первоочередной целью написания статьи было именно «разложить все по полочкам» для тех, кто уже работал с mysqli, но не вникал глубоко, а быстренько написал свои обертки и забыл про оригинальный синтаксис. Я постарался разъяснить нюансы, с которым столкнулся сам, при переносе данных из большой и очень старой БД, спроектированной человеком, не знающим про нормализации, в новую, с сильно изменившейся структурой.

Можно ли читать эту статью людям, которые все еще используют старое расширение mysql и только думающие об перехода на PDO или MySqli? Думаю даже нужно.

MySqli или PDO

Последние годы я писал сайты исключительно на фреймворках, что избавляло меня от работы с БД напрямую. Некоторое время назад начал работу над сайтом на чистом php и задался вопросом, что использовать вместо устаревшего и нерекомендованного к использованию старого расширения PHP MySQL.

Выбирать нужно было между MySqli и PDO. После не очень длительного изучения решил остановиться на MySqli, так как, как мне тогда казалось, он полностью идентичен PDO, за исключением того, что нет возможности отказаться от MySQL в пользу чего-то другого. Как я напишу ниже это не совсем так, минимум одно заметное отличие есть.

MySqli рекомендован к использованию самими разработчиками PHP.[1]

ООП и процедурный интерфейс

MySqli позволяет писать код как в ООП стиле так и в процедурном. Мне ближе ООП как и большинству из хабр сообщества, поэтому в этом статье будет использован именно он.

Три основные класса

Соединение с БД

Способ первый. Если вам нужно просто создать соединение.

Способ второй. Если вам нужно использовать опции соединения.

С помощью $mysqli->connect_errno и $mysqli->connect_error мы получаем описание и код ошибки, возникших при соединении. И new mysqli() и $mysqli->real_connect() при ошибках соединений вызывают ошибку PHP Warning. Поэтому вывод ошибок с помощью выше упомянутых функций имеет смысл, если у вас отключено отображение ошибок PHP, например, на рабочем сервере, либо если вам нужно как-то обработать эти данные. Я упомнил здесь об этом, потому что не все функции MySQLi вызывают PHP Warning в случае ошибки, и для того что бы узнать, что произошла ошибка необходимо обязательно обращаться к специальным функциям, об этом ниже.

Полученный при соединении объект мы присвоили переменной $mysqli, для того чтобы использовать его в дальнейшем. Это очевидно для ООП стиля, но и для процедурного стиля этот объект также необходим, в этом отличие от устаревшего расширения MySQL, где ссылку на соединение необязательно было передавать при каждом использовании mysql функций.

Буферизированные и не буферизированные результаты

Прежде чем рассказывать дальше, хотелось бы объяснить разницу между этими двумя типами результатов.

Рассмотрим небуферизированный результат. В этом случае вы можете начинать читать результаты, не дожидаясь пока mysql сервер получит результат полностью.

Буферизированный результат лишен этих недостатков и соответственно лишен перечисленных преимуществ.

«Классические» запросы

В MySqli оставили возможность «классических» запросов: когда пользователю предлагается самостоятельно заниматься безопасностью передаваемых запросов так, как это было в устаревшем расширении MySQL. Для этого предлагается использовать функцию $mysqli->real_escape_string(), с помощью которой необходимо обрабатывать все данные перед помещением их в запрос.

Так же как и с соединением есть два способа сделать такой запрос короткий и длинный.

Возможные константы:
MYSQLI_STORE_RESULT – вернет буферизированный результат, значение по умолчанию
MYSQLI_USE_RESULT – небуферизированный

Функции $mysqli->use_result() или $mysqli->store_result() так же используются при мульти запросах (запросах состоящих из нескольких запросов). Мульти запросы в этой статье рассмотрены не будут.

И тот и другой синтаксисы вернут результат в виде объекта mysqli_result, который представляет собой удобный интерфейс для работы с результатом, как с буферизированным так и не с небуферизированным.

Подготовленные запросы

Два способа создания подготовленного запроса.

Различия в том, для какого объекта вызываются функции получения информации об ошибке. Мне второй способ кажется удобнее, потому что проверки на ошибки можно объединить в один блок if c другими функциями mysqli_stmt. Как это сделать будет видно в примерах ниже.

Класс mysqli_result и работа с результатом с помощью него

Как было показано выше, объект mysqli_result вы могли получить как с помощью «классического» запроса с помощью класса mysqli, тогда он может быть как буферизированный так и небуферизированный, так и с помощью класса mysqli_stmt, тогда он буферизированный. От того какой результат вы получили, зависит работа функций этого класса, поэтому нужно хорошо понимать, что если ваш запрос небуферизированный вы не располагаете всем результатом и соответственно не можете знать сколько строк в результате, и читать его можно только по-порядку строка за строкой.

object ( Book ) [ 4 ]
private ‘some1’ => int 1
public ‘some2’ => int 2
protected ‘id’ => int 382

Источник

mysql_affected_rows

mysql_affected_rows — Возвращает число затронутых прошлой операцией рядов

Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:

Описание

Список параметров

Возвращаемые значения

Если последний запрос был DELETE без указания WHERE и, соответственно, таблица была очищена, функция вернёт ноль во всех версиях MySQL до 4.1.2.

При использовании UPDATE, MySQL не обновит колонки, уже содержащие новое значение. Вследствие этого, функция mysql_affected_rows() не всегда возвращает количество рядов, подошедших под условия, только количество рядов, обновлённых запросом.

Запрос REPLACE сначала удаляет запись с указанным первичным ключом, а потом вставляет новую. Данная функция возвращает количество удалённых записей вместе с количеством вставленных.

Примеры

Пример #1 Пример использования mysql_affected_rows()

Результатом выполнения данного примера будет что-то подобное:

Пример #2 Пример использования mysql_affected_rows() с транзакциями

Результатом выполнения данного примера будет что-то подобное:

Примечания

Замечание: Транзакции

При использовании транзакций mysql_affected_rows() нужно вызывать после запросов INSERT, UPDATE, DELETE, но не после COMMIT.

Замечание: Запросы SELECT

Замечание: Каскадные внешние ключи

mysql_affected_rows() не подсчитывает ряды, неявно изменённые ограничениями ON DELETE CASCADE и/или ON UPDATE CASCADE.

Смотрите также

User Contributed Notes 11 notes

So if you use one SQL request to insert several rows at a time, and some are inserted, some are just updated, you won’t get the real count.

SCENARIO
1. You’re using MySQL 4.1x with foreign keys.
2. You have table t2 linked to table t1 by a CASCADE ON DELETE foreign key.
3. t2 has a UNIQUE key so that duplicate records are unacceptable.
3. You have a REPLACE query on t1 followed by an INSERT query on t2 and expect the second query to fail if there’s an attempted insert of a duplicate record.

PROBLEM
You notice that the second query is not failing as you had expected even though the record being inserted is an exact duplicate of a record previously inserted.

CAUSE
When the first query (the REPLACE query) deletes a record from t1 in the first stage of the REPLACE operation, it cascades the delete to the record that would be duplicated in t2. The second query then does not fail because the «duplicate» record is no longer a duplicate, as the original one has just been deleted.

calling mysql_affected_rows(null)
is not the same that calling mysql_affected_rows()

if($link)
$n=mysql_affected_rows($link);
else
$n=mysql_affected_rows();

Note that when the CLIENT_FOUND_ROWS connection flag was used, affected_rows returns the number of rows matched by the WHERE condition of an UPDATE query, even if the query doesn’t actually change those rows. I.e. for

INSERT INTO t(id, val) VALUES (1, ‘x’);
UPDATE t SET val = ‘x’ WHERE />
the number of affected rows will be 0 normally but 1 with CLIENT_FOUND_ROWS.

Here’s a little function I’ve been using for a while now, pass it two parameters (action command (1 or 0 see notes)) and a sql statement.

I’ve found this invaluable when trying to tie down large amounts of updates to a table, using this you can easily see where a query was successfully executed and the number of rows are affected, or where there are problems and a statement has failed for example.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *