Can’t get variables to work in WPDB UPDATE query

I’ve tried all I can but this query will not work. I’ve tried prepare, adding ‘ to both variables, adding ‘ to only the SET variable, using springf, using a formatted string where both values are inserted into %s, nothing works. I’ve spent the whole night on this and right now I just feel like crying.

This query works when I hard-code the values or paste the dump directly in phpmyadmin.

Read More
$trans = strval($_POST["trans"]);
$status = strval($_POST["status"]);

global $wpdb;
$wpdb->show_errors;
$query = "UPDATE donations SET donation_status='".mysql_real_escape_string($status)."' WHERE donation_reference = '".mysql_real_escape_string($trans)."'";

$result = $wpdb->query($query);

$wpdb->print_error;

exit( var_dump( $wpdb->last_query ) );

Another funny thing is the query works when I replace the first two lines with hard-coded values, like:

$trans = "12345678";
$status = "Transaction Successful";

But as long as the values are read from the $_POST variables, the query doesn’t work.

I’m using PHP Version 5.3.28 and MySQL 5.5.40.

Please help!

Related posts

Leave a Reply

2 comments

  1. First of all, make sure $_POST contains what you expect.

    Then for added security, use wpdb::update() method instead of wpdb::query()

    $trans = strval($_POST["trans"]);
    $status = strval($_POST["status"]);
    
    global $wpdb;
    $wpdb->show_errors;
    $wdpb->update(
        'donations',
        array( 'dontion_status' => $status ),
        array( 'donation_reference' => $trans ),
    );
    $wpdb->print_error;
    
    exit( var_dump( $wpdb->last_query ) );
    
  2. I think I had the same issue. Setting variables for the UPDATE and WHERE sections of the query solved it. So, for your code, using the suggested $wdpb->update method, it would be:

    $status = strval($_POST["status"]);
    $trans = strval($_POST["trans"]);
    
    $table_name = 'donations';
    $data_update = array( 'dontion_status' => '$status' );
    $data_where = array('id' => '$id');
    
    global $wpdb;
    $wpdb->update($table_name, $data_update, $data_where, array('%s'), array('%d'));
    
    exit( var_dump( $wpdb->last_query ) );