skip to Main Content

So I ran a php file where I’m connecting it to a Database and executing a query, but I ended up getting an error stating

Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘SELECT SUM(total) FROM orders
WHERE created_at >= ( CURDA’ at line 1

but executing these queries will properly result in the query box in SQL as intended.

Here is the php file.

<?php

    $username = "examplename";
    $password = "abcdefg";
    $dbname = "exampledb";

    $conn = mysqli_connect('localhost', $username, $password, $dbname);
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $fifteenDaysTotal = "SELECT SUM(total)  FROM orders 
                        WHERE created_at >= ( CURDATE() - INTERVAL 15 DAY ) AND orderstatus_id=5
                        ORDER BY created_at DESC";

    $sql = "UPDATE `earnings` SET amount = $fifteenDaysTotal";

    if ($conn->query($sql) === TRUE) {
        echo "Record updated successfully";
    } else {
        echo "Error updating record: " . $conn->error;
    }


$conn->close();
?>

Thank you

2

Answers


  1. You are not storing the result of the query, you are just making that query equal to amount in the $sql query.

    Just make the following change:

    $fifteenDaysTotal_query= "SELECT SUM(total) AS total FROM orders 
    WHERE created_at >= ( CURDATE() - INTERVAL 15 DAY ) AND orderstatus_id=5 ORDER BY 
    created_at DESC";
    
    $query_total=$conn->query($fifteenDaysTotal_query);
    $row_total=$query_total->fetch_assoc();
    $fifteenDaysTotal=$row_total['total'];
    
    Login or Signup to reply.
  2. Update as the below statement. This is a sub query and we need to group this statement.

     $fifteenDaysTotal = "(SELECT SUM(total) FROM orders WHERE created_at >= ( CURDATE() - INTERVAL 15 DAY ) AND orderstatus_id=5 ORDER BY created_at DESC)"; 
    
     $sql = "UPDATE earnings SET amount = $fifteenDaysTotal";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search