Mysqli error no database selected

How to fix no database selected MySQL error Posted on Dec 02, 2021 Learn how to resolve no database selected MySQL error The error no database selected frequently occurs in MySQL when you perform a statement without selecting a database first. In the following example, I tried to query a students table immediately after […]

Содержание

  1. How to fix no database selected MySQL error
  2. Level up your programming skills
  3. About
  4. [FIX] MySQL ERROR 1046 (3D000) No Database Selected
  5. Why you are getting MySQL Error 1046 (3D000) No database selected?
  6. Steps to resolve MySQL ERROR 1046 (3D000) No Database Selected:
  7. Step 1:
  8. Step 2: Select the database
  9. Step 3: Execute statement
  10. Conclusion:
  11. No database selected. Проблема с подключением
  12. nameivan
  13. c0dex
  14. nameivan
  15. Фанат
  16. c0dex
  17. nameivan
  18. c0dex
  19. nameivan
  20. Фанат
  21. nameivan
  22. nameivan
  23. Фанат
  24. nameivan
  25. Фанат

How to fix no database selected MySQL error

Posted on Dec 02, 2021

Learn how to resolve no database selected MySQL error

The error no database selected frequently occurs in MySQL when you perform a statement without selecting a database first.

In the following example, I tried to query a students table immediately after connecting to the mysql command line:

To resolve this error, you need to first select a database to use in the command line by running the USE command:

You need to replace [database_name] with the name of a database that exists in your MySQL server.

You can also list the names of all databases available on your server with the SHOW DATABASES command.

The following shows the output on my computer:

Next, issue the USE command as shown below:

The error should be resolved once mysql responds with Database changed as shown above.

The same applies when you’re using a graphical user interface for managing MySQL databases like MySQL Workbench or Sequel Ace.

Just run the USE command before running any other statements:

The error can also happen when you run a .sql script file from the command line without adding a USE command:

To run the .sql file, you need to add a USE statement inside the SQL file itself.

Alternatively, you can also select the database you want to use from the command line as follows:

You need to add your database name after the -p option and before the symbol.

And that’s how you can resolve the error no database selected in MySQL database server 😉

Level up your programming skills

I’m sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Nathan Sebhastian is a software engineer with a passion for writing tech tutorials.
Learn JavaScript and other web development technology concepts through easy-to-understand explanations written in plain English.

Источник

[FIX] MySQL ERROR 1046 (3D000) No Database Selected

This article is a step-by-step guide to resolve the “MySQL ERROR 1046 (3D000) No Database Selected” error. If you are a DBA or a developer, this post will help you fix this MySQL 1046 error.

If you are getting this error message means you are trying to execute MySQL queries statement using the MySQL command prompt. Let’s go through why we get the error 1046 (3D000) followed by the step-by-step procedure to resolve this error.

Why you are getting MySQL Error 1046 (3D000) No database selected?

Let me tell you first why you are getting this 1046 MySQL error message. You might have guessed it right by now; the error message is pretty clear that you have not selected the database before executing your MySQL statement.

This error generally occurs when you try to create a Table in the MySQL database using the command prompt.

Because while executing a command from the command prompt you need to select the database also since MySQL will not be able to know for which database you are executing the script.

When you execute create table statement from MySQL workbench then at that time you need to manually select the database then you execute your statement. Similarly, while executing a script from the command prompt screen, make sure you have provided the database name.

The next question is “how to provide the database name?” No worries. Here are the steps; just follow the below steps by step procedure to get rid of the error.

Steps to resolve MySQL ERROR 1046 (3D000) No Database Selected:

Step 1:

  • Open MySQL command prompt.
  • Go to the start menu and open MySQL Command Line Client.

Step 2: Select the database

If you know the database name:

  • Select the Database on which you want to execute your script.
  • If you know the name of the database, then enter the database name in the following format.

use ;

Note: Don’t skip this step, this is the solution to get rid of the 1046 (3D000) error message.

If you do not know the database name:

If you don’t know the available database names or the database on which you are going to execute the script, then you can list all available databases using the following command.

SHOW databases;

Show database command lists down all the databases available. Then you run use ;

Step 3: Execute statement

Once the database is selected, you can execute your required SQL statement. Here we will execute create table statement in the database as an example.

That’s it. You can see the created table in the MySQL database using MySQL workbench.

Conclusion:

Is it not simple? I hope you now know the reason behind the “MySQL error 1046 No Database selected error” issue and how to fix it. Do share your feedback if this post helped you to fix the MySQL 1046 (3D000) error using the above steps in the comment section.

Источник

No database selected. Проблема с подключением

nameivan

Новичок

Всем привет!
Итак, есть файл connect.php, который предполагается подключать в скриптах

И есть файл index.php и в нем же форма авторизации

c0dex

web.dev 2002-.

nameivan

Новичок

Фанат

oncle terrible

Найди любое руководство по работе с mysql из РНР. Там написано.

Другое дело, что функций mysql_connect в РНР уже три года ка нету, но ты продолжай ими пользоваться.

c0dex

web.dev 2002-.

nameivan

Новичок

Найди любое руководство по работе с mysql из РНР. Там написано.

Другое дело, что функций mysql_connect в РНР уже три года ка нету, но ты продолжай ими пользоваться.

c0dex

web.dev 2002-.

@nameivan, дружище, ты не обижайся, просто ну что мы могли ожидать от человека, который на форуме с 2008 года, то есть 10+ лет? Ну минимум думали, что ты в теме более-менее.

Заменили mysql на mysqli, можешь так же посмотреть на PDO, в мане есть все.

nameivan

Новичок

@nameivan, дружище, ты не обижайся, просто ну что мы могли ожидать от человека, который на форуме с 2008 года, то есть 10+ лет? Ну минимум думали, что ты в теме более-менее.

Заменили mysql на mysqli, можешь так же посмотреть на PDO, в мане есть все.

Фанат

oncle terrible

nameivan

Новичок

Немного переделал, но ошибка.
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, null given in Z:. connect.php on line 9

При попытке залогиниться:
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, null given in Z:. connect.php on line 9
Warning: mysqli_query() expects at least 2 parameters, 1 given in Z. index.php on line 12
Warning: mysqli_error() expects exactly 1 parameter, 0 given in Z:. index.php on line 13

Не понимаю. Помогите, пожалуйста!

герр M:)ller

nameivan

Новичок

ок.
Устанавливает базу данных, которая будет использоваться при выполнении запросов к базе данных
Замечание:
Эта функция используется только для смены базы данных во время подключения. Вы можете выбрать базу данных, передав ее четвертым параметром в функции mysqli_connect().

Для примера там указано $link = mysqli_connect(«127.0.0.1», «my_user», «my_password», «my_db»);

И в моем файле прописано $connect = mysqli_connect($servername, $username, $password, $dbname);

Ну и где ошибка?

Фанат

oncle terrible

nameivan

Новичок

Бл. До чего же глупая ошибка
$result=mysqli_query($link, «SELECT count(*) FROM `users` WHERE `login` = ‘».$_POST[‘login’].»‘ AND `password` = ‘».MD5($_POST[‘pass’]).»‘;»)

Спасибо всем, кто старался помочь!

Фанат

oncle terrible

Это не глупая.
А вот `login` = ‘».$_POST[‘login’] — это действительно глупая.
Такого рода «авторизация» позволяет заходить кому угодно.
Чем делать так, лучше вообще авторизацию не ставить.

Источник

The error no database selected frequently occurs in MySQL when you perform a statement without selecting a database first.

In the following example, I tried to query a students table immediately after connecting to the mysql command line:

mysql> SELECT * FROM students;

ERROR 1046 (3D000): No database selected

To resolve this error, you need to first select a database to use in the command line by running the USE command:

You need to replace [database_name] with the name of a database that exists in your MySQL server.

You can also list the names of all databases available on your server with the SHOW DATABASES command.

The following shows the output on my computer:

mysql> SHOW DATABASES;

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| school_db          |
| sys                |
| test_db            |
+--------------------+

Next, issue the USE command as shown below:

mysql> USE school_db;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> 

The error should be resolved once mysql responds with Database changed as shown above.

The same applies when you’re using a graphical user interface for managing MySQL databases like MySQL Workbench or Sequel Ace.

Just run the USE command before running any other statements:

USE school_db;
SELECT * FROM students;
SELECT * FROM cities;

The error can also happen when you run a .sql script file from the command line without adding a USE command:

mysql -uroot -p < ./files/query.sql
Enter password: 

ERROR 1046 (3D000) at line 1: No database selected

To run the .sql file, you need to add a USE statement inside the SQL file itself.

Alternatively, you can also select the database you want to use from the command line as follows:

mysql -uroot -p school_db < ./files/query.sql   
Enter password: 

id	name
3	Bristol
4	Liverpool
1	London
2	York

You need to add your database name after the -p option and before the < symbol.

And that’s how you can resolve the error no database selected in MySQL database server 😉

This article is a step-by-step guide to resolve the “MySQL ERROR 1046 (3D000) No Database Selected” error. If you are a DBA or a developer, this post will help you fix this MySQL 1046 error.

If you are getting this error message means you are trying to execute MySQL queries statement using the MySQL command prompt. Let’s go through why we get the error 1046 (3D000) followed by the step-by-step procedure to resolve this error.

Why you are getting MySQL Error 1046 (3D000) No database selected?

MySQL ERROR 1046 (3D000) No Database Selected

Let me tell you first why you are getting this 1046 MySQL error message.  You might have guessed it right by now; the error message is pretty clear that you have not selected the database before executing your MySQL statement.

This error generally occurs when you try to create a Table in the MySQL database using the command prompt.

Because while executing a command from the command prompt you need to select the database also since MySQL will not be able to know for which database you are executing the script.

When you execute create table statement from MySQL workbench then at that time you need to manually select the database then you execute your statement. Similarly, while executing a script from the command prompt screen, make sure you have provided the database name.

The next question is “how to provide the database name?” No worries. Here are the steps; just follow the below steps by step procedure to get rid of the error.

Steps to resolve MySQL ERROR 1046 (3D000) No Database Selected:

Step 1:

  • Open MySQL command prompt.
  • Go to the start menu and open MySQL Command Line Client.

MySQL command line client

Step 2: Select the database

If you know the database name:

  • Select the Database on which you want to execute your script.
  • If you know the name of the database, then enter the database name in the following format.

use <database_name>;

select and use a database in MySQL

Note: Don’t skip this step, this is the solution to get rid of the 1046 (3D000) error message.

If you do not know the database name:

If you don’t know the available database names or the database on which you are going to execute the script, then you can list all available databases using the following command.

SHOW databases;

Show database command lists down all the databases available. Then you run use <database_name>;

Show database in MySQL

Step 3: Execute statement

Once the database is selected, you can execute your required SQL statement. Here we will execute create table statement in the database as an example.

mysql create table no database selected fix - table created

That’s it. You can see the created table in the MySQL database using MySQL workbench.

Table created in MySQL

Conclusion:

Is it not simple? I hope you now know the reason behind the “MySQL error 1046 No Database selected error” issue and how to fix it. Do share your feedback if this post helped you to fix the MySQL 1046 (3D000) error using the above steps in the comment section.

Cheers !!!

Similar article:
1. Fix “unknown collation ‘utf8mb4_unicode_520_ci’” Error

Mysql no database selected error causesMySQL no database selected is an error that occurs when you execute a statement without first selecting a database. The database may be completely missing, or you may choose the wrong database if there is more than one database.

Therefore, if you have more than one database, know the currently selected database and on which database your query execution takes place. Read this article to understand MySQL error and how to fix it.

MySQL No Database Selected Error Causes

The MySQL1046 (3D000) error occurs when you do not select a database first when executing the MySQL statement. This error will mostly happen if you are trying to create a table in the MySQL database using the command prompt. While executing a command from the command prompt, you must also select the database. Otherwise, MySQL will not know from which database you are running the script.

MySQL has a command to help you determine the currently selected database. This is a quick way to help you ascertain if the problem is genuinely caused by not specifying a database. If the error arises due to not selecting a database, you can easily overcome it by replacing [database_name] with the correct database name in your server.

When creating a table statement from the MySQL workbench, you need to select the database to run before executing the statement. Note, the process of choosing the database is manual, not automatic. Similarly, when running a script from the command prompt screen, ensure that you provide that database name.

How to Resolve the No Database Selected Error During File Import

The error code 1046 no database selected MySQL workbench will pop up if you do not select a database before importing the SQL file. This can be disappointing if you do not know the origin of the problem. Now that you know the reason, here are some quick fixes.

– Create a New Database

  • You must mention the name of the database prior to creating a table. To do so, use the command: USE database_name;
  • If the database is not there, create a new database. Creating a new database can be quickly done by using the command: CREATE DATABASE database_name;

Now, use the newly created database with the command USE database_name. This should eliminate the 1046 error.

– Workbench Solution

This solution is specifically efficient when using the workbench. Experts suggest that you follow the steps below to eliminate the error:

  • Find the welcome window, navigate to the left pane, and Object the browser
  • From the drop-down list, select a database of interest
  • Go to the SQL Development in the Workbench splash screen, look for the Manage Connections icon, and click on it.

– PhpMyAdmin Error Fix

This solution works for No database selected PhpMyAdmin errors. The approach tells you how you can resolve the error during the import. Just follow the steps below:

  • Have a new database ready on Live Site (the company hosting you, e.g., Bluehost). This is mandatory.
  • Navigate to phpMyAdmin on the live site and log in to the database
  • Choose a database of interest from the list on the left side of the page. Usually, there is a grey bar on top with a PHPMyadmin inscription, and below it are two options – information_schema and the name of the database you logged into.
  • From the top bar, click on the import button.
  • Find and click on the Browse button, browse the files to find the SQL file you created or of interest and click to open it when you see it. If the file is zipped, unzip it first.
  • Select SQL as the file format and press the Go button

After pressing the Go button, you will wait for a few minutes before seeing the results. Typically, the amount of wait time depends on the size of the database. The name of the created database must be similar to the name mentioned in the file. Otherwise, it will still throw the error.

– Other Solutions for Database Not Selected Error

One of the solutions requires that you create a database first before importing it. Here is the procedure.

  • Create a new database using MySQL phpMyAdmin
  • Use the database by simply running the command use database_name

And, finally, the easiest solution among all as it allows you to select a database using the command:

mysql -u example_user -p –database=work < ./work.sql

How to View Currently Selected Database: Avoiding MySQL No Database Selected Error

If you want to view the presently selected database, use the MySQL command below:

SELECT DATABASE();

You can execute this command from both two points – MySQL command line or MySQL workbench. The procedure for both processes is pretty straightforward.

If you are accessing it from the workbench, open it and execute the command:

SELECT DATABASE();

This action will expose the currently selected database, i.e., it returns the database you have selected. Usually, the database is also displayed in bold on the left side.

If you are working from the MySQL terminal, you must log in using your username and password and execute the command:

SELECT DATABASE();

This action also presents the selected database. However, the command will return null if you have not selected a database. This is common when you log into the terminal for the first time.

How to Import Files to Mysql Correctly

When the error emerges on your screen, you know the real cause of the issue. But, do you know how to select the database in MySQL? So, if you encounter a ”no database selected” error in PHP, Python, or any other program, you didn’t import your file correctly. Here is how you can import the files:

1. The step one is opening the Command :

  • Open the command prompt on MySQL
  • Navigate to the start menu and open Command Line Client.

2. The second step is selecting the Database:

  • Selecting the database takes two forms: first, if you know the database, and second, if you do not know the database.

3. Let’s look at the first case (you know the database name):

  • Select the database you wish to execute your script
  • Do you know the name of the database? If yes, enter it in the format, use <database_name>;

Knowing the database name is critical since it is a solution to getting rid of the 1046 (3D000) error message.

4. Let’s look at the second option (you do not know the database name):

  • In case you don’t know the database or database name on which you want to execute the script, list all the databases available using the command SHOW databases;
  • This command, i.e., SHOW databases, will list all available databases making it easy to spot the database of interest.
  • Run the use <database_name> command to select the database you want

5. And now we can execute the Statement:

  • After you successfully select a database of interest, execute the needed statement. Typically, you will be executing create table statement in the database. This action creates a table in the database in MySQL using the workbench.

FAQ

– How Do I Switch Between Mysql Databases?

If you have more than one database in MySQL, indicate each with the USE command. This command helps you select or switch between databases in a MySQL server. However, you must choose the correct database each time you switch databases or start a new MySQL session.

– How Do I Select a Schema in Mysql?

Right-click on MySQL connection from the home screen and select edit connect. Set the desired default schema on the Default Schema box. The schema you select will be displayed in bold in the schema navigator. Use Filter to This Schema functionality to target specific schemas in the list.

Conclusion

Error 1046 usually occurs if you do not select the correct database when importing files in MySQL. That’s what we have discussed in detail in this article. The main points in this article are:

  • Always select the database before clicking the import button
  • Use the command SELECT Database when selecting a specific database in MySQL to work with when you have multiple databases. However, if you have one database, use SQL command USE.
  • When MySQL ERROR 1046 (3D000) occurs, ensure you select the database. You can use the exact name to locate the file. Otherwise, use the command SHOW databases. This command displays all databases letting you select the right one.
  • The first step in preventing the 1046 error is learning how to import files.

How to fix mysql no database selected errorFirst, we have shown you how to import files correctly, and second, we have given you tips on how to solve the error 1046 when it occurs. These fixes are pretty straightforward, so why can’t you start applying them today?

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

15 ответов

Вам нужно указать MySQL, какую базу данных использовать:

USE database_name;

прежде чем создавать таблицу.

Если база данных не существует, вам необходимо создать ее как:

CREATE DATABASE database_name;

а затем:

USE database_name;

codaddict
23 окт. 2010, в 18:35

Поделиться

Вы также можете указать MySQL, какую базу данных использовать (если она уже создана):

 mysql -u example_user -p --database=example < ./example.sql

Shay Anderson
17 фев. 2014, в 19:47

Поделиться

Я столкнулся с такой же ошибкой, когда попытался импортировать базу данных, созданную ранее. Вот что я сделал, чтобы исправить эту проблему:

1- Создать новую базу данных

2- Используйте его с use команды

Изображение 881

3- Повторите попытку

Это работает для меня.

Mina Fawzy
06 дек. 2015, в 09:44

Поделиться

Если вы пытаетесь сделать это с помощью командной строки…

Если вы пытаетесь запустить оператор CREATE TABLE из интерфейса командной строки, вам нужно указать базу данных, в которой вы работаете, перед выполнением запроса:

USE your_database;

Здесь документация.

Если вы пытаетесь сделать это через MySQL Workbench…

… вам нужно выбрать соответствующую базу данных/каталог в раскрывающемся меню, расположенном над вкладкой «Обозреватель объектов: вкладка». Вы можете указать стандартную схему/базу данных/каталог для подключения — нажмите «Управление соединениями» в разделе «Развитие SQL» экрана заставки Workbench.

Добавление

Все это предполагает наличие базы данных, в которой вы хотите создать таблицу внутри — если нет, вам нужно создать базу данных прежде всего:

CREATE DATABASE your_database;

OMG Ponies
23 окт. 2010, в 19:40

Поделиться

Если вы делаете это через phpMyAdmin:

  • Я предполагаю, что вы уже создали новую базу данных MySQL на Live-сайте (на живом сайте я имею в виду компанию, в которой ваш хостинг (в моем случае Bluehost)).

  • Перейдите в phpMyAdmin на сайте live — войдите в базу данных, которую вы только что создали.

  • Теперь ВАЖНО! Прежде чем нажимать кнопку «импорт» на верхней панели, выберите свою базу данных в левой части страницы (серая полоса, сверху вверху написан PHP Myadmin, под ней два параметра: information_schema и имя базы данных, в которую вы только вошли.

  • после того, как вы щелкнете базу данных, которую вы только что создали/вошли в нее, она покажет вам эту базу данных и затем щелкните параметр импорта.

Это трюк для меня. Надеюсь, что поможет

Roanna
18 март 2014, в 01:40

Поделиться

  • Отредактируйте свой SQL файл, используя Блокнот или Блокнот ++
  • добавьте следующую строку:

CREATE DATABASE NAME;
USE NAME;

Ayham AlKawi
11 окт. 2013, в 21:40

Поделиться

Если вы импортируете базу данных, вам нужно сначала создать ее с тем же именем, затем выбрать ее, а затем импортировать в нее существующую базу данных.

Надеюсь, что это сработает для вас!

ivan n
25 окт. 2011, в 17:44

Поделиться

цитирование ivan n:
«Если вы импортируете базу данных, вам нужно сначала создать ее с тем же именем, а затем выбрать ее, а затем импортировать в нее существующую базу данных.
Надеюсь, это сработает для вас! «

Это следующие шаги:
Создайте базу данных, например my_db1, utf8_general_ci.
Затем нажмите, чтобы войти в эту базу данных.
Затем нажмите «импорт» и выберите базу данных: my_db1.sql

Это должно быть все.

iversoncru
18 апр. 2013, в 13:56

Поделиться

сначала выберите базу данных: USE db_name

тогда таблица creat: CREATE TABLE tb_name
(  id int,
 имя varchar (255),
 зарплата int, город варчар (255)
);

this для синтаксиса версии mysql 5.5

veeru666
04 июль 2015, в 13:13

Поделиться

Для MySQL Workbench

  1. Выберите базу данных со вкладки Схемы, щелкнув правой кнопкой мыши.
  2. Установить базу данных как схему по умолчанию

Изображение 882

Eric Korolev
06 дек. 2018, в 14:36

Поделиться

Я опаздываю, думаю:] Сори,

Если вы здесь, как я, ища решение, когда эта ошибка возникает с mysqldump вместо mysql, попробуйте это решение, которое я нашел на немецком веб-сайте, случайно, поэтому я хотел поделиться с бездомными людьми, у которых были головные боли, подобные мне.

Таким образом, проблема возникает из-за отсутствия параметра -databases перед именем базы данных

Поэтому ваша команда должна выглядеть так:

mysqldump -pdbpass -udbuser --databases dbname

Другая причина проблемы в моем случае заключалась в том, что я развивается на локальном компьютере, а у пользователя root нет пароля, поэтому в этом случае вы должны использовать --password= вместо -pdbpass, поэтому моя последняя команда:

mysqldump -udbuser --password= --databases dbname

Ссылка на полный поток (на немецком языке): https://marius.bloggt-in-braunschweig.de/2016/04/29/solution-mysqldump-no-database-selected-when-selecting-the-database/

MoolsBytheway
23 сен. 2018, в 03:56

Поделиться

Для дополнительного элемента безопасности при работе с несколькими БД в том же script вы можете указать БД в запросе, например. msgstr «создать таблицу my_awesome_db.really_cool_table…».

William T. Mallard
17 июль 2016, в 16:22

Поделиться

Просто хотел добавить: если вы создаете базу данных в mySQL на живом сайте, перейдите в PHPMyAdmin, и база данных не появится — выход из cPanel, затем войдите в систему, откройте PHPMyAdmin, и он должен быть там сейчас.

the10thplanet
05 авг. 2014, в 00:57

Поделиться

Хотя это довольно старый поток, я только что нашел что-то. Я создал новую базу данных, затем добавил пользователя и, наконец, пошел использовать phpMyAdmin для загрузки файла .sql. общий сбой. Система не распознает, к какой базе данных я стремился…

Когда я начинаю новый БЕЗ с первого присоединения нового пользователя, а затем выполняет тот же импорт phpMyAdmin, он отлично работает.

zipzit
27 сен. 2013, в 11:01

Поделиться

jst создайте новую базу данных в mysql. Выберите этот новый DB. (если вы используете mysql phpmyadmin сейчас, то наверху он будет похож на «Сервер: ... * → База данных). Теперь перейдите на вкладку импорта, выберите файл. Импорт!

cs075
19 окт. 2015, в 07:27

Поделиться

Ещё вопросы

  • 1Fileupload hasfile возвращает false при первой обратной передаче
  • 1Как программно отключить Outlook в проекте AddIn 2010?
  • 1DependencyProperty объекта UserControl равен нулю, если элемент UserControl имеет DataContext.
  • 0Перенаправить на другой угол обзора
  • 1XML выберите узел sing и переберите его
  • 1_.bindAll не работает при визуализации представления Backbone
  • 1Как преобразовать общее количество секунд в строку в формате «часы, минуты, секунды» [дубликаты]
  • 0Фонд раскрывает не распознает модальную ссылку
  • 0Переполнение CloudZoom скрыто
  • 0Fancybox не работает с определенным селектором
  • 1Как мне зашифровать App.config для Azure WebJob?
  • 0C ++ unordered_map не находит значения из аргументов командной строки
  • 1Python WordPress_XMLRPC NewComment Auth
  • 0php получает информацию о фейсбуке, используя имя пользователя и пароль
  • 1CXF wsdl2java не разрешающий каталог
  • 1Класс символов в Java
  • 0HTML / CSS страница входа проблемы со стилем в IE не работает
  • 0Как сделать так, чтобы поле редактирования отображалось в позиции элемента, нажатой с угловым
  • 0Сохранять данные $ _POST после перенаправления
  • 1Может ли Android <селектор> быть основан на состоянии объекта вместо состояния представления?
  • 0Примечание: неопределенный индекс: идентификатор пользователя в C: xampp htdocs locallocal admin userUpdate.php в строке 5
  • 0Использование левого соединения и сохранение значения левого идентификатора таблицы
  • 0CSS для печатных СМИ, чтобы показать бегущую страницу на определенных страницах
  • 0построение меню в HTML с содержанием справа
  • 0Проверка формы Laravel 5.6 уникальна
  • 1Разница забитых и пропущенных голов в Кубке Мира 2018 года
  • 0Обратный инжиниринг Enterprise Architect с shared_ptr <TYPE>
  • 0Угловой JS с ASP.NET Master Pages
  • 1Сохранение оригинального обратного вызова «this» с помощью функции bind
  • 1Сохранить значения, прежде чем закрыть приложение?
  • 0Каков современный способ не дублировать код на HTML-страницах и подстраницах?
  • 1Переопределение требует, чтобы начать с корня и проверить модули узла без изменения его имени
  • 0как проверить данные по тексту?
  • 1Панды для Loop Optimization
  • 1JTextArea и DocumentFilter выводят текущий текст
  • 1Как контролировать межстрочный интервал между текстами GTK
  • 0Проблемы с вызовом хранимой процедуры mySQL через функцию Node.JS
  • 1Java: заменить набор символов другими символами
  • 1многопроцессорность дает AssertionError: демоническим процессам не разрешено иметь детей
  • 0Как я могу получить и управлять потоковым ресурсом БД? PHP-DB2
  • 0Как я могу получить информацию о странице в Solr?
  • 0Рендеринг шрифта и маржа в Safari 5 — 6 и Chrome
  • 1сервлет не передает атрибут сеанса в jsp
  • 0Как я могу напечатать результат добавления функции ..?
  • 1Получение правильных заголовков таблицы с векторами jswing
  • 1Упаковать более 1 виджета в приложение для Android
  • 0Установить заголовок Content-Type в multipart?
  • 0mysql комплексная сумма, разделенная на COUNT
  • 1Использование python для создания гистограммы с нечисловой осью X
  • 0Как выполнить код PHP после его автоматического создания с использованием конкатенации строк?

  • #1

Всем привет!
Итак, есть файл connect.php, который предполагается подключать в скриптах

Код:

<?php
$host = 'localhost'; // адрес сервера
$database = 'base'; // имя базы данных
$user = 'root'; // имя пользователя
$password = ''; // пароль
?>

И есть файл index.php и в нем же форма авторизации

Код:

<?php
session_start();
?>
<head>
<title></title>
</head>
<body>
<div align="center">
<?php
require_once 'connect.php';
$link = mysql_connect($host, $user, $password, $database)
    or die("Ошибка " . mysql_error($link));
    if(isset($_POST['login']) && isset($_POST['pass'])){
     $sql = mysql_query("SELECT count(*) FROM `users` WHERE `login` = '".$_POST['login']."' AND `password` = '".MD5($_POST['pass'])."';")
            or die(mysql_error());
        $row = mysql_fetch_assoc($sql);
        if($row['count(*)']>0){
            $_SESSION['login'] = $_POST['login'];

            echo '<meta http-equiv="refresh" content="0;URL=main.php">';
exit();
        }else{
            echo '<strong>Введен не верный логин/пароль!</strong>';
        }
    }
?>
<form action="" method="post">

<table>
  <tr>
    <td  colspan="3" align="center">Логин</br><input type="text" size="20" name="login"/></td>
  </tr>
  <tr>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr>
    <td colspan="3" align="center">Пароль</br><input type="password" size="21"  name="pass"/></td>
  </tr>
  <tr>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr>
  <td><div align="right"><input type="submit" name="Submit" value="      Вход      "></div></td>
  <td>&nbsp;&nbsp;</td>
  <td><div align="left"><input type="reset" name="Submit2" value="    Отмена    "></div></td>
</tr>
</table>
</form>
</div>
    </div>
</div>
</body>
</html>

Сама страница загружается, но при вводе логина и пароля получаю сообщение No database selected.
Помогите разобраться где я ошибся. Параметры подключения прописаны верно.

c0dex


  • #2

Ошибся в месте, где делаешь первый запрос, а базу не выбрал.

  • #3

Можете ткнуть меня носом? Весь день ищу ошибку, уже глаз замылился

Фанат


  • #4

Найди любое руководство по работе с mysql из РНР. Там написано.

Другое дело, что функций mysql_connect в РНР уже три года ка нету, но ты продолжай ими пользоваться.

c0dex


  • #5

Можете ткнуть меня носом? Весь день ищу ошибку, уже глаз замылился

Где у тебя первый запрос? Вот перед ним ты должен был выбрать БД, из таблиц которой ты делаешь выборки. Как выбрать БД — написано в мануале

  • #6

Найди любое руководство по работе с mysql из РНР. Там написано.

Другое дело, что функций mysql_connect в РНР уже три года ка нету, но ты продолжай ими пользоваться.

Можно было и без сарказма. Я не являюсь профессиональным программистом. То, что сейчас пытаюсь сделать делаю больше для себя. Это во-первых. А во-вторых, раз уж довели до моего сведения тот факт, что mysql_connect в РНР уже три года ка нету, то могли бы и сообщить чем же заменили.
Вопрос то был сформулирован нормально, вежливо.

c0dex


  • #7

@nameivan, дружище, ты не обижайся, просто ну что мы могли ожидать от человека, который на форуме с 2008 года, то есть 10+ лет? Ну минимум думали, что ты в теме более-менее.

Заменили mysql на mysqli, можешь так же посмотреть на PDO, в мане есть все.

  • #8

@nameivan, дружище, ты не обижайся, просто ну что мы могли ожидать от человека, который на форуме с 2008 года, то есть 10+ лет? Ну минимум думали, что ты в теме более-менее.

Заменили mysql на mysqli, можешь так же посмотреть на PDO, в мане есть все.

Зарегистрирован давно, но давно не кодил. Не было надобности, а тут вот решил вспомнить немного. и сразу затык на подключении к базе. Т.е. сначала сделал проще, но неудобно в каждом скрипте прописывать линки. Захотел сделать файлом.

Фанат


  • #9

дело тут совсем не в файле.
верни все как было, с прописыванием в каждом файле, и попробуй потом еще раз с файлом
пойми, форум — не для поиска опечаток.

  • #10

Немного переделал, но ошибка.
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, null given in Z:………….connect.php on line 9

При попытке залогиниться:
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, null given in Z:…………..connect.php on line 9
Warning: mysqli_query() expects at least 2 parameters, 1 given in Z:…………………..index.php on line 12
Warning: mysqli_error() expects exactly 1 parameter, 0 given in Z:…………..index.php on line 13

Не понимаю. Помогите, пожалуйста!

Код:

<?php
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname= "base";

  // Create connection
  $connect = mysqli_connect($servername, $username, $password, $dbname);
  mysqli_set_charset ( $conn , "utf8");

  // Check connection
  if (!$connect) {
   die("Ошибка подключения к БД: " . mysqli_connect_error());
 }
?>

Код:

<?php
session_start();
?>
<head>
<title></title>
</head>
<body>
<div align="center">
<?php
require_once 'connect.php';
if(isset($_POST['login']) && isset($_POST['pass'])){
$result=mysqli_query("SELECT count(*) FROM `users` WHERE `login` = '".$_POST['login']."' AND `password` = '".MD5($_POST['pass'])."';")
or die(mysqli_error());
$row = mysqli_fetch_assoc($result);
if($row['count(*)']>0)
  {
   $_SESSION['login'] = $_POST['login'];
   echo '<meta http-equiv="refresh" content="0;URL=main.php">';
   exit();
  } else {echo '<strong>Введен не верный логин/пароль!</strong>';}
        // освобождение используемой памяти
        mysqli_free_result($result);
        // Закрываем соединение
        mysqli_close($connect);   
}
?>
<form action="" method="post">
<table>
  <tr>
    <td  colspan="3" align="center">Логин</br><input type="text" size="20" name="login"/></td>
  </tr>
  <tr>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr>
    <td colspan="3" align="center">Пароль</br><input type="password" size="21"  name="pass"/></td>
  </tr>
  <tr>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr>
  <td><div align="right"><input type="submit" name="Submit" value="      Вход      "></div></td>
  <td>&nbsp;&nbsp;</td>
  <td><div align="left"><input type="reset" name="Submit2" value="    Отмена    "></div></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</body>
</html>

WMix


  • #12

ок.
Устанавливает базу данных, которая будет использоваться при выполнении запросов к базе данных
Замечание:
Эта функция используется только для смены базы данных во время подключения. Вы можете выбрать базу данных, передав ее четвертым параметром в функции mysqli_connect().

Для примера там указано $link = mysqli_connect(«127.0.0.1», «my_user», «my_password», «my_db»);

И в моем файле прописано $connect = mysqli_connect($servername, $username, $password, $dbname);

Ну и где ошибка?

Фанат


  • #13

ВСЕГДА error_reporting(E_ALL); самой первой строчкой.

  • #14

Бл…. До чего же глупая ошибка
$result=mysqli_query($link, «SELECT count(*) FROM `users` WHERE `login` = ‘».$_POST[‘login’].»‘ AND `password` = ‘».MD5($_POST[‘pass’]).»‘;»)

Спасибо всем, кто старался помочь!

Фанат


  • #15

Это не глупая.
А вот `login` = ‘».$_POST[‘login’] — это действительно глупая.
Такого рода «авторизация» позволяет заходить кому угодно.
Чем делать так, лучше вообще авторизацию не ставить.

Запросы так не пишутся никогда
Как писать запросы читаем здесь: http://php.net/manual/ru/security.database.sql-injection.php
После этого здесь http://php.net/manual/ru/function.password-hash.php, выкинуть md5 и использовать password_hash

в итоге получаем такой код

PHP:

$stmt = $link->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $_POST['email']);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if ($user && password_verify($_POST['pass'], $user['pass']))
{
    echo "valid!";
} else {
    echo "invalid";
}

fixxxer


  • #17

Вот не люблю эту картинку, ну какой sanitize? Насмотрелся я тут этих sanitize в индусском коде, include «sanitize.php», со стандартной бредятиной а-ля magic quotes на все.
(Да, я зануда).

  • #18

— «OConnor»?
— Нет, «O’Connor».
— Таких у нас базе нет, до свидания. Мы научились санировать данные.

fixxxer


  • #19

Таких у нас базе нет, до свидания.

Exactly!

PHP:

 $data = file_get_contents("php://input");
-$data  =       str_replace("'","",$data);
 $records = json_decode($data, true);

(Я уже не пощу в «индусский код», туда можно постить вообще весь проект).

  • #20

Вот не люблю эту картинку, ну какой sanitize? Насмотрелся я тут этих sanitize в индусском коде, include «sanitize.php», со стандартной бредятиной а-ля magic quotes на все.
(Да, я зануда).

Я тоже устал писать в комментариях, что слово «sanitize» стоит заменить на «mangling», чтобы лучше был понятен результат действия.

Понравилась статья? Поделить с друзьями:
  • Mysqli error exception
  • Mysqli error 500
  • Mysqli error 1054
  • Mysqli connect php error
  • Mysqli connect error 2002 no such file or directory