使用 php 查询不起作用 [英] query doesn't working using php
问题描述
我是 PHP 和 MYsql 的新手,我正在尝试使用 php 创建一个包含变量的简单查询.但是我认为我没有用变量正确地编写查询,因为这个查询的结果是 0.
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);
?>
推荐答案
$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 .
所以让我们创建一个文件 configDB.ini 并放入数据库信息
So let's create a file configDB.ini for example and put in db informations
servername = something;
username = something;
password = something;
dbname = something;
完成后,我们可以创建一个名为 dbconn.php 的脚本并使用凭据导入文件,通过这种方式,凭据和连接之间存在抽象.
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 .
在 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);
最后说一下mysqli_query
你应该使用 MySQLi 扩展而不是 MySQL 扩展的原因有很多:
Reasons why you should use MySQLi extension instead of the MySQL extension are many:
从 PHP 5.5.0 起 mysql 被弃用并引入了 mysqli
from PHP 5.5.0 mysql is deprecated and was introduced mysqli
为什么选择mysqli(优势)
Why choose mysqli (strenghts)
面向对象
准备好的陈述
许多功能
无注射
这篇关于使用 php 查询不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!