Criticism in favor of connecting to DB:

$db_host = "localhost"; $db_user = "root"; $db_pass = ""; $db_name = "new_db"; define ("IMG" , "img"); $link = mysqli_connect($db_host , $db_user , $db_pass , $db_name) OR DIE ("Не могу подключится"); if (mysqli_connect_errno()) { printf("Ошибка соединения: %s\n", mysqli_connect_error()); exit; } $query = mysqli_select_db($link , $db_name) OR DIE ("Не моу выбрать базу, либо она отсутствует"); $result = mysqli_query($link , "SELECT `title` , `text` , `img` FROM `news` "); while($row = $result->fetch_assoc()) {?> <div class="post"> <h2><?= $row['title'];?></h2> <img src="IMG/<?= $row['img'];?>" title="" /> <p><?= $row['text'];?></p> </div> <?}?> 

what's in the error code, how would you improve or improve it? the code outputs from the DB without errors, everything works but:

  • And what is the question? What comes after "but:"? - Ipatiev
  • let's say how to separate the view from the controller? individually does not work, at least include at least include_once - user33274
  • What? Oh, got it. Do not use words whose meanings you do not understand - this makes it difficult to understand what you need. If you do not know how to use include, then this is the way to write - they say, the problem with connecting a file to the PHP script. - Ipatiev
  • Yes, like I said correctly - I can explain in more detail what is needed, the fact is that if I make the name.php file and write down all $ var and do include in the right place, it just stops working and everything, as well as the connection itself same in another file and also include and also ceases to work - user33274
  • Rewrite your question, show how you do include. - Ipatiev

1 answer 1

Two things should be corrected in this code:

  1. Make normal error handling.
  2. Remove duplicate code.

Thus, the connection code will be as follows:

 <?php $db_host = "localhost"; $db_user = "root"; $db_pass = ""; $db_name = "new_db"; mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect($db_host , $db_user , $db_pass , $db_name); 

This code can be saved in a file, and it can be included wherever you need a connection to the database

  • And how to remove the while itself with index.php and leave only {?> <?}?> This? - user33274
  • I repeat, if you have a problem with include, then it is better to ask a new, separate question, which is entitled “How to use include correctly”, and describe your own problems in it. - Ipatiev