Yassine Qoraiche
Yassine Qoraiche

Reputation: 31

Insert data of custom metabox to database

How can I insert data values of custom metaboxes into a database to the corresponding field in a table?

This is how I tried to get the values for each form:

$l = $_POST['liens'];
$post_id = $_POST['post_ID'];
$langue = $_POST['lang'];
$qual = $_POST['qual'];
$type = $_POST['type'];
if (isset($l) and !empty($l) )
mysql_query("insert into blog_liens values('','".$post_id."','".$l."','".$langue."','".$qual."','".$type."',now(),'','1') ");

But it's not working.

Upvotes: 1

Views: 1080

Answers (2)

Nathan Dawson
Nathan Dawson

Reputation: 19318

Always use $wpdb when handling database in WordPress but that's not applicable here anyway.

Add this to the same file as your metabox.

function my_metabox_save_value( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    if ( ! current_user_can( 'edit_post' ) ) return;

    if ( isset( $_POST['lang'] ) )
        update_post_meta( $post_id, 'lang', sanitize_text_field( $_POST['lang'] ) );
}
add_action( 'save_post', 'my_metabox_save_value' );

Repeat update_post_meta for each value you want to save and add your own checks if needed such as ! empty().

Ideally you would also be using a nonce but that's beyond the scope of the question. For further info please see: http://codex.wordpress.org/WordPress_Nonces and http://codex.wordpress.org/Function_Reference/add_meta_box

Upvotes: 1

MaiKaY
MaiKaY

Reputation: 4482

  1. please escape the post parameters for example with mysql_real_escape_string
  2. dont use mysql_* functions -> use mysqli or PDO for your Queries

Have you tried to debug? ;)

$result = mysql_query('SELECT foo FROM bar');
if(!$result ){
    echo mysql_error();
    exit;
}

Upvotes: 0

Related Questions