Mysql fetch assoc ошибка

You don’t need to prevent this error message!
Error messages are your friends!
Without error message you’d never know what is happened.
It’s all right! Any working code supposed to throw out error messages.

Though error messages needs proper handling.
Usually you don’t have to to take any special actions to avoid such an error messages. Just leave your code intact.
But if you don’t want this error message to be shown to the user, just turn it off. Not error message itself but daislaying it to the user.

ini_set('display_errors',0);
ini_set('log_errors',1);

or even better at .htaccess/php.ini level
And user will never see any error messages. While you will be able still see it in the error log.
Please note that error_reporting should be at max in both cases.

To prevent this message you can check mysql_query result and run fetch_assoc only on success.
But usually nobody uses it as it may require too many nested if’s.
But there can be solution too — exceptions!

But it is still not necessary. You can leave your code as is, because it is supposed to work without errors when done.

Using return is another method to avoid nested error messages. Here is a snippet from my database handling function:

  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbget: ".mysql_error()." in ".$query);
    return false;
  }
  if (!mysql_num_rows($res)) return NULL;

  //fetching goes here
  //if there was no errors only

Here there are two things you have to notice :

1) the warning with mysql_fetch_assoc() .
This warning will occur when the argument passed to it is not an vaide mysql resource ,ie,
the mysql_connect() returned null object(failed to return conection object) . This inturn is caused due to fact that arguments passed to mysql_connect() are bad database credentials.

this case is usualy traped by using

is_resource($con) 

call which returns true if $con is an valid resource.

2) The error as described in the error discription is due to bad syntax of query.

"SELECT * FROM logs WHERE log_name='$report_id"  

here you ommited closing brace for $report_id

"SELECT * FROM logs WHERE log_name='$report_id'"

3) data base access :
An generel method of accesing database is by using an class , that access the database credentials through Accessor methods like setUname() , SetPasswd() etc , where the method itself will trim , escape and sanitize the credentials before it is passed to database.
this will prevent sql injection attack

В коде не могу разобраться почему скрипт не выводит картинки. А выдает ошибку » Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\OpenServer\domains\localhost\lessons\php\index.php on line 33″
Ошибка как вы поняли находится на 33 строчке или на 36, просто код скопировал без html каркаса.

$connection = mysql_connect('localhost', 'Heartofprogramme', '123321');
         $db = mysql_select_db('test_db');

         if(!$connection || !$db){
            exit(mysql_close());
         }

         $result = mysql_query(" SELECT * FROM news LIMIT 3");

         mysql_close();

         while($row = mysql_fetch_assoc($result)): ?>
         <div class="items_news">
           <h1><? echo $row['title']?></h1>
           <p class="text"><?  echo $row['text']?></p>
           <p class="date">Дата публикации: <?  echo $row['date']?></p>
           <p class="time">Время публикации: <?  echo $row['time']?></p>
           <p class="author">Автор статьи: <?  echo $row['author']?>
         </div>
         <? endwhile;

         // Код картинки!

         $connection = mysql_connect('localhost', 'Heartofprogramme', 'ahmedborec');
         $db = mysql_select_db('test_db');

         if(!$connection || !$db){
            exit(mysql_close());
         }

         $result_two = mysql_query(" SELECT * FROM img where order by id ");

            mysql_close();

            while($row_two = mysql_fetch_assoc($result_two)){
              $avatar = $row_two['avatar'];
              $description = $row_two['description'];
              echo "
                      <img src='avatar/$avatar'>
                      <p>$description</p>
                   ";
            }
			 	?>


  • Вопрос задан

  • 7542 просмотра

$result_two = mysql_query(" SELECT * FROM img where order by id ");

ошибка в синтаксисе, уберите where или добавьте условие.

Пригласить эксперта

Так вы сначала соединение закрыли, а потом пробуете оттуда что-то достать…
И выбросьте mysql, используйте mysqli.

$result = mysql_query($connection, " SELECT * FROM news LIMIT 3");

Начнем с того, что $result_two=false. Почему? А потому, что ошибка при запросе. Не учили после каждого query проверять на ошибки?

Почему ошибка при запросе? Потому что не пишут «Выбрать все из ньюс где сортировать», на кой там where?

И последнее. Зачем верите тостеру, больше чем документации?
Вам пишут mysql_query($connection… и вы слепо пробуете, хотя в документации четко сказано mysql_query(query_string).


  • Показать ещё
    Загружается…

21 сент. 2023, в 15:53

10000 руб./за проект

21 сент. 2023, в 15:48

5000 руб./за проект

21 сент. 2023, в 15:38

5000 руб./за проект

Минуточку внимания

In this guide, we will discuss how to fix the mysql_fetch_assoc() error that occurs when the first parameter is expecting a resource instead of a boolean. This error usually occurs when there is a problem with the SQL query, and the mysql_query() function returns false. We will go through the possible causes of this issue and provide step-by-step solutions to resolve the error.

Table of Contents

  1. Understanding the Error
  2. Identifying the Causes
  3. Step-by-Step Solutions
  4. FAQs
  5. Related Links

Understanding the Error

The mysql_fetch_assoc() function is used to fetch a result row as an associative array in PHP. The function expects a resource as its first parameter, which is obtained from the mysql_query() function. If the mysql_query() function returns false, it indicates that there is an error in the SQL query, and the mysql_fetch_assoc() function will generate the following error:

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given

Identifying the Causes

There are several possible causes for this error. Some of the most common reasons are:

  1. Syntax errors in the SQL query
  2. Incorrect table or column names
  3. Insufficient user privileges for the database
  4. Connection to the database has not been established

Step-by-Step Solutions

To resolve the mysql_fetch_assoc() error, follow the steps below:

Step 1: Check SQL Query Syntax

Make sure your SQL query syntax is correct. You can verify the syntax by running the query directly in your database management tool (e.g., phpMyAdmin). If there are any syntax errors, correct them and update the query in your PHP code.

Step 2: Verify Table and Column Names

Ensure that the table and column names used in the SQL query match the actual names in your database. Table and column names are case-sensitive, so make sure to use the correct case.

Step 3: Check User Privileges

Verify that the database user has the necessary privileges to execute the SQL query. You can check the user’s privileges in your database management tool or by running a SHOW GRANTS query in your SQL console.

Step 4: Establish Database Connection

Make sure you have established a connection to the database before executing the SQL query. Use the mysql_connect() function to connect to the database and the mysql_select_db() function to select the desired database.

$connection = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $connection);

After following these steps, your mysql_fetch_assoc() error should be resolved.

FAQs

Why is the mysql_* function deprecated?

The mysql_* functions are deprecated since PHP 5.5.0 and removed in PHP 7.0.0. These functions are replaced with the more secure and efficient alternatives like MySQLi and PDO. It is recommended to use these alternatives for better security and performance.

How can I switch to MySQLi from the deprecated mysql_* functions?

To switch to MySQLi, you can follow these steps:

  1. Replace mysql_connect() with mysqli_connect().
  2. Replace mysql_select_db() with mysqli_select_db().
  3. Replace mysql_query() with mysqli_query().
  4. Replace mysql_fetch_assoc() with mysqli_fetch_assoc().
  5. Update other mysql_* functions with their respective MySQLi counterparts.

How can I display the actual error message from the SQL query?

To display the actual error message from the SQL query, you can use the mysql_error() function as follows:

$result = mysql_query($query);
if (!$result) {
    die('Error: ' . mysql_error());
}

How can I prevent SQL injection in my PHP code?

To prevent SQL injection, you should use prepared statements or parameterized queries. These features are available in both MySQLi and PDO. By using prepared statements, you can avoid including user input directly in the SQL query, which reduces the risk of SQL injection attacks.

Can I use the mysql_fetch_assoc() function with other database systems, such as PostgreSQL or SQLite?

The mysql_fetch_assoc() function is specific to the deprecated MySQL extension in PHP. To work with other database systems, you should use the appropriate PHP extension, such as PDO or the specific extension for the database system (e.g., pg_fetch_assoc() for PostgreSQL).

  • PHP: MySQL (Original) — Manual
  • PHP: MySQLi — Manual
  • PHP: PDO — Manual
  • How to Fix PHP Deprecated Features

Note: This guide is for educational purposes only, and it is recommended to switch to the more secure and efficient MySQLi or PDO extensions for working with databases in PHP.

3 ответа

У меня была одна и та же проблема на простой таблице с одним значением, я добавил сообщения об ошибке die, и она все еще ничего не показывала для меня, попробуйте отозвать одну конкретную строку таблицы, для меня она показала результат, поэтому я решил, проблема была в кодировке как json. Поэтому я использовал решение, найденное в json encoding, возвращающее пустую строку. Что касается эха вашей конкретной строки, я пробовал это:

$result = mysqli_query($conn, $query) or die(mysqli_error($conn));

if($result->num_rows > 0){
     while($row= mysqli_fetch_assoc($result)){
        echo($row['name_ofRow']);
   }
}

Надеюсь, это поможет некоторым образом.

ALEXANDRA LutinNoir

Поделиться

Как указано в комментариях, вы должны печатать фактическое сообщение об ошибке mysql вместо настраиваемых сообщений, это поможет вам в отладке ошибки,

Вот несколько советов по исправлению ошибки,

Ваш код должен быть:

<?php
include("C:\Wamp\www\system\db\connect.php"); //<-- You should give relative path instead of this one
$term = mysqli_real_escape_string($con, $_GET['q']);
echo "results for \"".$term."\".<br>";
$sql = "SELECT * FROM 'search' WHERE Keywords like '%{$term}%' LIMIT 10";
$result = mysqli_query($con, $sql) or die(mysqli_error($con)); //<-- show mysql error instead of custom one
while($row = mysqli_fetch_assoc($result) ) {
    echo $row['Title'];
}
echo json_encode($row['Title']);

mysqli_close($con);
?>

Apul Gupta

Поделиться

Замените следующие строки:

$sql = "SELECT * FROM 'search' WHERE Keywords='%{$term}%' LIMIT 10";
$result = mysqli_query($con, $sql) or die("<p color=\"#f00\">Could not query database.</p>");
while($row = mysqli_fetch_assoc($result) or die("<p color=\"#f00\">Could not fetch assoc array in database.</p>")) {
   echo $row['Title'];
}

с этими:

$sql = "SELECT * FROM 'search' WHERE Keywords LIKE '%{$term}%' LIMIT 10";
$result = mysqli_query($con, $sql) or die("<p color=\"#f00\">Could not query database.</p>");
while($row = mysqli_fetch_assoc($result) ) {
   echo $row['Title'];
}

NaijaProgrammer

Поделиться

Ещё вопросы

  • 1Автоматизировать установку ucbrowser
  • 0Отображение сообщения вне цикла while
  • 1Код Python 3.5 / 3.6 в зависимости от порядка вставки dict
  • 0PHP submit обновляет страницу и принимает идентификатор отправки в качестве параметра
  • 1SqlDependency не работает событие, если имеются очереди и запрос действителен
  • 0Раскрывающееся меню HTML удаляет пробелы между элементами LI
  • 0MYSQL Неправильное использование групповой функции Как разрешить?
  • 0Как добавить правило в редактор RichText с помощью плагина jquery.validate.js?
  • 1Клонировать массив с оператором распространения и добавить встроенный
  • 1Несоответствие типов шаблонов при обновлении данных плитки
  • 0Yii — Css — один активный эффект для нескольких ссылок
  • 1Одинаковые элементы массива
  • 0Проблемы при попытке применить класс CSS к строкам
  • 0CHtml :: link () не создает ссылку
  • 0Результаты glRotatef на Wirecube
  • 0Сравнение наборов данных с левым объединением, но предотвращение влияния нулевых значений на результаты
  • 1Несовместимые версии Gradle — Сервисы Google Play
  • 0Раскрывающийся список привязки в Angular JS, имеющий неправильное значение в опции
  • 0эхо UPLOADPATH. $ row [‘image’] не отображает имя файла
  • 0Проблема с повторяющимися кнопками поля формы
  • 1PageSpeed app.js и app.css блокируют рендеринг
  • 0C ++ — Использование ofstream для создания файла в другом каталоге?
  • 1Почему это возвращает значение в REPL Javascript?
  • 0Meshlabserver: не удается подключиться к X-серверу ошибка
  • 0Перспектива CSS3 не применяется до завершения анимации
  • 1Отключить асинхронную загрузку Google Analytics
  • 1Как установить значение месяца на основе количества
  • 1Невозможно создать экземпляр фрагмента androidx.navigation.fragment.NavHostFragment
  • 1JAXB: Вы должны указать каждое поле, которое будет включено?
  • 1Как заставить панды рассматривать каждую строку как столбец на основе определенной переменной даты? [Дубликат]
  • 0Переместить следующий узел назад
  • 1Android Runnable не выполняется MainLooper
  • 1C # AsyncSockets, куда отправлять данные без получения данных раньше?
  • 0Два всплывающих окна не работают должным образом
  • 1Как добавить поле на «plotLines text» Highcharts
  • 0cv :: putText в IplImages
  • 1Как сопоставить результат с оператором return действия, возвращающего объект в Struts 2?
  • 0Производные от синглтона: один объект каждый из базы и производные?
  • 0Возвращать переменные на фабриках Angular JS?
  • 0Изменяемая ручка блокирует перетаскиваемое взаимодействие
  • 0Нужно ли удалять этот объект? (если я не собираюсь когда-либо удаляться)
  • 0CSS: всплывающее окно расширения таблицы, даже с установленной шириной / максимальной шириной
  • 0Angular — Mocha — Тесты не выполняются, когда я добавляю несколько контроллеров к одному модулю
  • 1Как выбрать переменные в массиве (A) со значениями из переменной (B)
  • 0Ожидаемый возврат алгоритма поиска STL
  • 0Скрытие тела таблицы, когда все строки скрыты в angularjs
  • 1Android: загрузка в веб-представлении не работает в oreo, она принудительно закрывается на устройствах Oreo
  • 0Ошибка при вставке записи. Невозможно добавить или обновить дочернюю строку: ограничение внешнего ключа не выполнено
  • 0Синтаксис управления потоком без контейнеров в select не работает в IE8
  • 1Есть ли способ получения информации, отображаемой в работающем приложении Android?

Понравилась статья? Поделить с друзьями:
  • Mysql 500 ошибка
  • Mysql 42000 ошибка
  • Mysql 134 ошибка
  • Mysql 10054 ошибка
  • Myphoneexplorer ошибка obex errorcode c1 unauthorized