$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = $conn->query($sql);
Above there is a fast solution , but it is not safe ,
because is vulnerable to injection …
Below let’s see how to do it and why to do it in this way
It is a good practice to store sensible information in a separate file
out of the document root , it means will be not accesible from the web .
So let’s create a file configDB.ini for example and put in db informations
servername = something;
username = something;
password = something;
dbname = something;
Once did it we can create a script called dbconn.php and import the file with credentials ,
in this way there is an abstraction between credentials and connection .
in dbconn.php :
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
We can even improve the code connecting to db only once and use the same connection all the time we need query .
function db_connect() {
// static will not connect more than once
static $conn;
if(!isset($conn)) {
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
return $conn;
}
…
$conn = db_connect();
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = mysqli_query($conn,$sql);
In the end let’s say something about mysqli_query
Reasons why you should use MySQLi extension instead of the MySQL extension are many:
from PHP 5.5.0 mysql is deprecated and was introduced mysqli
Why choose mysqli (strenghts)
-
object oriented
-
prepared statements
-
many features
-
no injection
4
solved query doesn’t working using php