Mysqli_insert_id 返回 0 或 $con 未定义

Mysqli_insert_id returning 0 or $con not defined

我一直在尝试将我的 mysql 转换为在此之前工作的 mysqli。我大部分时间都在使用准备好的语句。我不确定 mysqli_insert_id 是如何写的,因为我尝试过的各种事情导致 0 或 $con 未定义,具体取决于代码。

准备好的语句

<?php


function db_connect() {

    // Define connection as a static variable, to avoid connecting more than once 
    static $con;

    // Try and connect to the database, if a connection has not been established yet
    if(!isset($con)) {
         // Load configuration as an array. Use the actual location of your configuration file
        $config = parse_ini_file('config.ini'); 
        $con = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
    }

    // If connection was not successful, handle the error
    if( $con === false) {
        // Handle error - notify administrator, log to a file, show an error screen, etc.
        return mysqli_connect_error(); 
    }
    return  $con;
}

function db_query($query) {
    // Connect to the database
     $con = db_connect();


    // Query the database
    $result = mysqli_query( $con,$query);

    return $result;
}

function db_error() {
     $con = db_connect();

        return mysqli_error($con);
}

function db_select($query) {
    $rows = array();
    $result = db_query($query);

    // If query failed, return `false`
    if($result === false) {
        return false;
    }

    // If query was successful, retrieve all the rows into an array
    while ($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
    }
    return $rows;
}
function db_quote($value) {
     $con = db_connect();

        return "'" . mysqli_real_escape_string($con,$value) . "'";
}
?>

插入代码并定义 $last_id。所有字段和值都是变量,插入一行没有问题。

 $result = db_query("INSERT INTO $table($col1,$col3,$col4,$col5) VALUES ('$field','$field3','$field4','$field5')");
    if($result === false) {
     $error = db_error();
     echo $error;}
     else {
        // We successfully inserted a row into the database

    $last_id = mysqli_insert_id($con);
    echo $last_id;

我使用 $last_id 填充另一个 table 以包含 last_id 的列。

就目前而言,这段代码显示了一个错误 Notice: Undefined variable: con in D:\xampp\htdocs\Websites\mindia\project.php on line 186

如果我在下面的任何函数之外声明 $con 并更改为 $last_id = mysqli_insert_id($con);,当我回显 $last_id

时我得到 0
static $con;
      if(!isset($con)) {
         // Load configuration as an array. Use the actual location of your configuration file
        $config = parse_ini_file('config.ini'); 
        $con = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
    }

我需要以某种方式使用 $last_id 以便我可以使用将显示 $last_id 的行填充另一个 table - 这是一个单独的脚本,如果需要,我将 post 那也是。

任何帮助将不胜感激。如果需要任何其他信息,请告诉我。

我又一次找到了我自己问题的答案,因为其他人都没有回答。

看来问题很容易解决。我查看了所有准备语句的代码,发现有一个 $con 变量定义为 db_connect 准备语句。

所以为了让它起作用我做了这个

$con= db_connect();
$last_id = mysqli_insert_id($con);

基本上这定义了变量 $con 并允许 mysqli_insert_id 使用它