Home > front end >  Error 500 When Updating MySql Database from WordPress - Same Code Works Fine Outside of WordPress
Error 500 When Updating MySql Database from WordPress - Same Code Works Fine Outside of WordPress

Time:11-10

I need to update a MySql database from inside a JS function within a WordPress Woocommerce page. I'm using Ajax to do this. The following code works fine as a stand-alone code but when I put it into the WordPress page (on my localhost) it throws an error 500. Also I put the required data (which will eventually be a variable) onto the end of the url (?test=14230) because I couldn't get it to send the data when using the data: line in the Ajax.

Here's the Ajax:

function db()
{
   
         $.ajax({
      url: 'update_db.php?test=14230',
      type: 'post',
      data: 0,
      success: function(output) 
      {
          alert('Success, server says ' output);
      }, error: function()
      {
          alert('Something went wrong.');
      }
   });
   
}

Here's the update_db.php:

<?php
if(isset($_GET['test']) ){
$id = $_GET['test'];
}
        
    include 'database-handler.php';
    
    $sql = "UPDATE db_name SET column = 'Some Value' WHERE id = $id";

    if(mysqli_query($conn, $sql)){
        //echo ('<p>'."Success.".'</p>');
    } else {
        //echo ('<p>'."Something went wrong. $sql. " . mysqli_error($conn).'</p>');
    }
    
    mysqli_close($conn);  
?>

So I'm just wondering why this works as a stand-alone code but not when it's inside WordPress?

Edit: Here is the error log:

[Wed Nov 09 15:16:47.543162 2022] [php:error] [pid 4564:tid 1828] [client ::1:5888] PHP Fatal error: Uncaught TypeError: mysqli_query(): Argument #1 ($mysql) must be of type mysqli, null given in C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php:17\nStack trace:\n#0 C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php(17): mysqli_query(NULL, 'UPDATE new_card...')\n#1 {main}\n thrown in C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php on line 17, referer: http://localhost/my-sites/wowcard/product/polka-dot-brush-strokes-two-photo-birthday-card-purple/?card=complete&id=14230

CodePudding user response:

The error was because of this line:

include 'database-handler.php';

Replacing the include with the contents of database-handler.php fixed the issue.

CodePudding user response:

WordPress has its own database handler which is automatically loaded, there are most likely conflicts between your code and WordPress, but without seeing the actual error, I can not give more information.

Check this out https://developer.wordpress.org/reference/classes/wpdb/

Example:

global $wpdb;
$results = $wpdb->query($wpdb->prepare( 'UPDATE db_name SET column = 'Some Value' WHERE id = %d' , $id ));
  • Related