mysqli_prepare() 期望参数 1 是 mysqli

2021-12-25 00:00:00 php mysqli

在使用 mysqli

功能如下:

db.php

<?php
define("DB_HOST", "host");
define("DB_LOGIN", "login");
define("DB_PASSWORD", "password");
define("DB_NAME", "myDb");

$link = mysqli_connect(DB_HOST, DB_LOGIN, DB_PASSWORD, DB_NAME);
if(!$link) {
    echo 'ERROR: ' . mysqli_connect_errno() . ': ' . mysqli_connect_error();
}
?>

function.php

<?php
function addItemToCatalog($var1, $var2, $var3, $var4) {
    $sql = 'INSERT INTO catalog (var1, var2, var3, var4) 
            VALUES (?, ?, ?, ?)';
    if (!$stmt = mysqli_prepare($link, $sql)){
        return false;
    }
    mysqli_stmt_bind_param($stmt, "ssii", $var1, $var2, $var3, $var4);
    mysqli_stmt_execute($stmt); 
    mysqli_stmt_close($stmt); 
    return true;
}
?>

page.php

<?php
require_once ("db.php");
require_once ("function.php");

$var1 = $_POST['var1']; //showing without filtering methods
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
$var4 = $_POST['var4'];

if(!addItemToCatalog($var1, $var2, $var3, $var4)){ 
    echo 'some error text';
}
else { 
    header("Location: success.php"); 
    exit;
}
?>

使用后有

警告:mysqli_prepare() 期望参数 1 为 mysqli,第 5 行 function.php 中给出的 null.

WARNING: mysqli_prepare() expects parameter 1 to be mysqli, null given in function.php on line 5.

有人吗?

推荐答案

两个文件 db.phpfunction.php 粘在一起的方式我认为导致$link 被定义为全局变量 - 您需要使用 global 在函数内访问它:

The way the two files db.php and function.php are glued together I think results in $link being defined as a global variable - you need to use global to access it within function:

function addItemToCatalog($var1, $var2, $var3, $var4) {
    global $link;
    ...
}

或通过参数显式地将$link给函数:

or give the $link to the function explicitly through parameter:

function addItemToCatalog($var1, $var2, $var3, $var4, $link) {
    ...
}

相关文章