Skip to content
Advertisement

SQL error when inserting a function variable

I try to use a value resulted from a 1st function as argument into a 2nd function, but SQL give me the error cannot be NULL

Erreur de la base de données WordPress : [Column 'option_price' cannot be null]
INSERT INTO `wp_options_prices` (`option_name`, `option_value`, `option_price`) VALUES ('single-checkbox---3499163', 'Location du système vidéo : 5€', NULL)

My 1st function :

function get_option_price($option_name,$option_value) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'options_prices'; 

    $optionprix = $wpdb->get_var("SELECT option_price FROM `$table_name` WHERE option_name = '$option_name' AND option_value = '$option_value'");
    echo $optionprix;

$wpdb->show_errors();
}

My php who call the 2nd function :

<?php 
$optionprix = get_option_price($field['name'],$field['value']);
set_option_price($field['name'],$field['value'],$optionprix);
echo $optionprix;
?>

My 2nd function :

function set_option_price($option_name,$option_value,$option_price) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'options_prices'; 

$data = array('option_name' => $option_name, 'option_value' => $option_value, 'option_price' => $option_price);

$wpdb->insert($table_name,$data);

$wpdb->show_errors();
}

Echo is ok, it print correctly my value, but trying to use it as argument for my 2nd function don’t work.

If I include $optionprix = “10” my 2nd function work fine.

Advertisement

Answer

You’re not actually returning the option price from your get_option_price function which is why $option_price is NULL. Add a return:

function get_option_price($option_name,$option_value) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'options_prices'; 

    $optionprix = $wpdb->get_var("SELECT option_price FROM `$table_name` WHERE option_name = '$option_name' AND option_value = '$option_value'");
    echo $optionprix;

    $wpdb->show_errors();
    return $optionprix;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement