【发布时间】:2015-02-09 14:32:56
【问题描述】:
我一直在尝试将我的 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 的行 - 这是一个单独的脚本,如果需要,我也会发布它。
任何帮助将不胜感激。如果需要任何其他信息,请告诉我。
【问题讨论】: