I am stumped by a problem that has been bugging me for a few days now and cannot seem to find solution for it.
In my application’s back-end, I use a MySQL query in PHP to get table-name, stored in another table (bank_accounts), and then I store that value in a variable. Like so:
Table name – bank_accounts | Accessing table_name column from this
$getbankledgername = "SELECT table_name FROM bank_accounts WHERE bank_name='Himalaya Bank' AND bank_acholder = 'New Hira Itta Udyog'";
if($res = mysqli_query($con, $getbankledgername)) {
$brow = mysqli_fetch_assoc($res);
$bln = $brow['table_name'];
echo($bln);
$fetchBankBalance = "SELECT bl_balance from $bln ORDER BY bl_id DESC LIMIT 1";
if($bankresult = mysqli_query($con, $fetchBankBalance)) {
$bankrow = mysqli_fetch_assoc($bankresult);
$bankbalance = $bankrow['bl_balance'];
$newbankbalance = $amount + $bankbalance;
$bankParticular = 'Cheque deposited of '.$custname;
$bls = "INSERT INTO `{$jmd}` (`bl_id`, `bl_date`,`bl_part`, `bl_debit`,
`bl_credit`,`bl_balance`) VALUES (null, '{$date}','{$bankParticular}','{$amount}','000000',
'{$newbankbalance}')";
if(mysqli_query($con,$bls)) {
http_response_code(204);
$transaction = [
'bl_date' => $date,
'bl_part' => $bankParticular,
'bl_debit' => $amount,
'bl_credit' => '000000',
'bl_balance' => $newbankbalance,
'bl_id' => mysqli_insert_id($con)
];
echo json_encode($transaction);
}
else{return http_response_code(422);}
}
}
PHP Code
When I run this code in Postman, I get the following results –
bledger_himalaya_bank_nhiu
Fatal error: Uncaught
mysqli_sql_exception: Table ‘nhiu_accounting.bledger_himalaya_bank’
doesn’t exist in C:xampphtdocsbackendapichequesduetest.php:52
Stack trace:
#0 C:xampphtdocsbackendapichequesduetest.php(52): mysqli_query(Object(mysqli), ‘INSERT INTO `bl…’)
#1 {main} thrown in C:xampphtdocsbackendapichequesduetest.php on line
52
As you can see, the echo of the table name variable returns correct value, which is bledger_himalaya_bank_nhiu, but somehow the same variable when it is used in the query to insert data, returns error that table does not exist. But the table that Postman shows to be wrong is just a cut short version of the required table name (nhiu_accounting.bledger_himalaya_bank) minus the _nhiu part.
What is going on here? I am utterly confused. Any help will be much appreciated.