0

I have a main page on my site and I am trying to make a connection to the MySQL server and get some data from the database. But the problem is that when I want to establish a connection I have to put the username and password in the page which doesn't seem wise to me.

I added a part of my code related to this problem.

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";

$connection = new mysqli($host , $userName , $password , $dbName);
if ($connection->connect_error) {
    die("Connection failed due to this error : " . $connection->connect_error . '<br>');
}
else{
    echo "Connected successfully";
{
</body>
</html>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Sina
  • 15
  • 5
  • If your server is configured correctly, nobody can download a php script. So its fine – RiggsFolly Jan 19 '21 at 13:50
  • Should be fine. PHP is executed on the server side, and any output is sent to the client. This shouldn't be visible to anyone unless they have access to your server. – GrumpyCrouton Jan 19 '21 at 13:52
  • Also https://stackoverflow.com/questions/46897705/why-mysqli-connect-must-receive-the-password-parameter-with-no-encryption and https://stackoverflow.com/questions/15088979/php-and-mysql-how-to-avoid-password-in-source-code – Dharman Jan 19 '21 at 14:09
  • 1
    You need to stop manually checking for errors. Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) and [Should I manually check for errors when calling “mysqli_stmt_prepare”?](https://stackoverflow.com/q/62216426/1839439) – Dharman Jan 19 '21 at 14:10

2 Answers2

0

Put your connection code into another file, like connection.php and in every page you want to connect you should require_once "connection.php", also you could use variables from that file if you connect it, also instead of require_once you can use just require, but look at the internet differences between them

V.D.
  • 1,215
  • 1
  • 7
  • 17
-1

Normal practice is to put the mysql data in a separate php file. For example:

dbmain.php

<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";

$connection = new mysqli($host , $userName , $password , $dbName);



?>

then you can include this file in all php files which require db connection.

<?php include_once("dbmain.php"); ?>
<!DOCTYPE html>

<html lang="en">
<head>
</head>
<body>
<?php

/// php commands, such as

//if ($result = $mysqli -> query("SELECT * FROM dbtable1")) {
//  echo "Returned rows are: " . $result -> num_rows;
//   Free result set
//  $result -> free_result();
//}
//$mysqli -> close();


?>
</body>
</html>
Ken Lee
  • 6,985
  • 3
  • 10
  • 29