0

I am trying to SELECT data from 1 database and insert into another, but I have problem in INSERT.

I get this error PHP Fatal error: Uncaught Error: Call to a member function execute() on boolean when I run my code.

MY CODE

<?php
include 'db_acc.php'; 
include 'db_sat.php'; 

$sql = "SELECT created_at,updated_at
        FROM satellite1.show_activity";
$result=$conn1->query($sql);

while($row = $result->fetch_assoc()) {
    echo "$row[updated_at]"; // I can get the value
    
$sql2 = "INSERT INTO analysis_account.currency SET
            id=0,
            currency_code='MYR',
            currency_rate= 3.500,
            currency_unit= 100,
            base_currency= 1,
            created_by= 2,
            updated_by= 2,
            created_at= '2021-05-17 14:10:32',
            updated_at = ".$row["updated_at"].", // But I cant insert the value
            curr_hidden = 1 ";

$query=$conn2->query($sql2);

}
$conn2->close();
?>

The problem is I can get the value of $row[updated_at] but I cant insert it into other database table, the connection is no problem because if I change $row[updated_at] into '2021-05-17 14:10:32' then the insert statement work.

I checked my connection, column names, symbols there are no problem of them. I really dont know what to do to solve the error.

LJ27
  • 109
  • 2
  • 15
  • Maybe a typo? $conn2 instead of $conn1? – tino.codes Aug 12 '21 at 06:45
  • Your code doesn't call `execute()`, so how can the error be generated here? – Nigel Ren Aug 12 '21 at 06:48
  • Nope, I checked it already, I can insert value by simply change ```$row[updated_at] ```into ```'2021-05-17 14:10:32'``` so i think it wont be typo – LJ27 Aug 12 '21 at 06:48
  • @NigelRen I used```$query=$conn2->query($sql2);``` this will execute the $sql so I dont need to call execute(). – LJ27 Aug 12 '21 at 06:49
  • 1
    You should be using prepared statements anyway - https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Nigel Ren Aug 12 '21 at 06:50
  • 1
    My point was that your error doesn't match your code! Sometimes changing the code can make the error not reproducible and therefore can waste others time. If the code calls a function which wraps the error, then please include that as well as it may be the cause of the error. – Nigel Ren Aug 12 '21 at 06:52

1 Answers1

3

Your INSERT query is missing quotes around the timestamp value. Just change

updated_at = ".$row["updated_at"].",

to

updated_at = '".$row["updated_at"]."',

This would fix the insert functionality but your code remains susceptible to SQL injection attacks. Please avoid simple string concatenation in your SQL queries and prefer prepared statements with placeholders.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89