I'm trying to get the ID of the last record inserted in my phpMyAdmin table, but I only get 0's so far.
I have tried almost everything (for example the solution on this answer: a link or what this page recommend : a link ) but I can't get it working.
My table has a column id that is the primary key and is marked as AUTO_INCREMENT.
I use a function query that make the connection to the database and then execute the queries:
function query($sql) {
$conn = mysqli_connect ( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
// Check connection
if (mysqli_connect_errno ()) {
echo 'connection failed: ' . mysqli_connect_error ();
}
// Check if the server is alive
if (mysqli_ping ( $conn )) {
// echo 'Connection is ok';
} else {
echo 'Error: ' . mysqli_error ( $dbc );
}
$sql = mysqli_query ( $conn, $sql );
$last_id = mysqli_insert_id( $conn );
$num_rows = mysqli_num_rows ( $sql );
$result = mysqli_fetch_assoc ( $sql );
return array (
"num_rows" => $num_rows,
"result" => $result,
"sql" => $sql,
"last_id" => $last_id
);
mysqli_close($conn);
}
Then I have another function from where I called the first one to execute the query:
function reg_shp_add($address_type, $company_name, $country, $state, $city, $zip, $street_name, $street_number, $tel){
if($address_type=="residential"){
$my_address_type = "r";
}else{
$my_address_type = "c";
}
$this->query ( "INSERT INTO `Addresses` (`company_name`, `street_address`, `address_two`, `zip_code`, `city_name`, `state_id`, `country_id`, `phone_number`, `res_comm_add`, `date_entered`) VALUES ('$company_name', '$street_name', '$street_number', '$zip', '$city', '$state', '$country', '$tel', '$my_address_type', CURRENT_TIMESTAMP)" );
$address_id = $sql ['user_id'];
$customer_id = $_COOKIE['userId'];
$this->query ( "INSERT INTO `Cust_address_type` (`cust_id`, ` mail_address_id`, `address_type`) VALUES ('$customer_id', '$address_id', 'Shipping')" );
return 'Address was saved.';
}
I first tried to retrieve the last id from my reg_shp_add function, but I guess it must be done from the first one.
Can anybody help me please?