提问人:R4E Group 提问时间:3/26/2020 最后编辑:DharmanR4E Group 更新时间:3/26/2020 访问量:588
如何通过函数参数 [duplicate] 传递 SQL 字符串
How to pass SQL string via function parameter [duplicate]
问:
我想创建以 SQL 字符串为参数并返回一个数组的函数 我写这个函数:
function getgquery($I_sql){
$mysqli = new mysqli("localhost","root","","ACLUB");
$sql = $I_sql;
$result = $mysqli->query($sql);
$Data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$Data [] = $row;
}
}
return $Data;
}
然后调用函数:
print_r(getgquery('SELECT * FROM `poeple`'));
但是我收到此错误:
警告:mysqli_num_rows() 期望参数 1 mysqli_result, 在第 9 行的 N:\xampp\htdocs\test\functions.php 中给出的布尔值
答:
1赞
Dharman
3/26/2020
#1
这是个好主意!
您收到错误是因为您尚未启用错误报告,并且您没有看到您在 SQL 中输入的拼写错误。
正确的函数应如下所示:
// Enable mysqli error reporting and open connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'db_test');
$mysqli->set_charset('utf8mb4'); // always set the charset
function getgquery(mysqli $mysqli, string $I_sql, array $params = []): ?array {
$stmt = $mysqli->prepare($I_sql);
if ($params) {
$stmt->bind_param(str_repeat("s", count($params)), ...$params);
}
$stmt->execute();
if ($result = $stmt->get_result()) {
return $result->fetch_all(MYSQLI_BOTH);
}
}
// with the typo fixed:
print_r(getgquery($mysqli, 'SELECT * FROM `people`'));
- 您需要在函数外部连接一次,并将连接作为参数传递。
- 您需要使用准备好的语句!
- 摆脱这个无用的循环和
num_rows
如果您认为每次都向此函数传递连接太多,则可以创建mysqli的子类,例如:
class DBClass extends mysqli {
public function __construct(
$host = null,
$username = null,
$passwd = null,
$dbname = null,
$port = null,
$socket = null
) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
parent::__construct($host, $username, $passwd, $dbname, $port, $socket);
$this->set_charset('utf8mb4');
}
public function safeQuery(string $sql, array $params = []): ?array {
$stmt = $this->prepare($sql);
if ($params) {
$stmt->bind_param(str_repeat("s", count($params)), ...$params);
}
$stmt->execute();
if ($result = $stmt->get_result()) {
return $result->fetch_all(MYSQLI_BOTH);
}
return null;
}
}
然后像这样使用它:
$mysqli = new DBClass('localhost', 'username', 'password', 'db_test');
$result = $mysqli->safeQuery('SELECT * FROM people WHERE id=?', [$myId]);
评论
poeple
people