Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

mysql - query doesn't working using php

I am new in Php and MYsql, I am trying to create a simple query using which contain a variable using php. however I think I am not writing the querty correctly with the variable since the result of this query is 0.

would be happy for assistance here is my code:

<?php
$phone = $_GET['phone'];
echo $phone;
    $query = "SELECT * FROM `APPUsers` WHERE `Phone` LIKE "."'".$phone."' ";
    echo $query;
    $result = mysqli_query($mysqli, $query);
    echo mysqli_num_rows($result);
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...