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来填充另一个表,以包含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的行填充另一个表——这是一个单独的脚本,如果需要,我也会发布它。

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

在没有其他人回复的情况下,我再次找到了自己问题的答案。

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

所以为了让它发挥作用,我做了这个

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

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