avatar
retrieve the id from database table MySQL

• Be assumption that we create user table with a simple structure as below:

CREATE TABLE `users` (
  `id` bigint(20) NOT NULL,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `role_id` int(11) NOT NULL,
  `created_at` datetime NOT NULL DEFAULT current_timestamp(),
  `updated_at` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

• Retrieve the user ID from a database table called `users` based on a given email.

$table_user = 'users';

$user_id = $wpdb->get_var(
    $wpdb->prepare(
        "SELECT id FROM $table_user WHERE email LIKE %s",
        '%' . $email . '%'
    )
);

or

$user_id = $wpdb->get_var(
    $wpdb->prepare(
        "SELECT id FROM $table_user WHERE role_id = %d",
        $role_id
    )
);

• Use an array to specify multiple columns in the SQL query and retrieve the corresponding values using $wpdb->get_row() or a similar method.

$table_user = $wpdb->prefix . "users";
$columns = array('id', 'username', 'email');

$user_data = $wpdb->get_row(
    $wpdb->prepare(
        "SELECT " . implode(", ", $columns) . " FROM $table_user WHERE email LIKE %s",
        '%' . $email . '%'
    )
);

if ($user_data) {
    $user_id = $user_data->id;
    $username = $user_data->username;
    $email = $user_data->email;
    
    // Use the retrieved data as needed
    // ...
}

• Insert user into a user table based on the provided script, you can modify it as follows:

$username = wp_strip_all_tags($_POST['username']);
$email = wp_strip_all_tags($_POST['email']);
$password = wp_strip_all_tags($_POST['password']);

$table_user = $wpdb->prefix . "users";

$wpdb->insert($table_user, array(
    'username' => $username,
    'email' => $email,
    'password' => $password,
    'created_at' => current_time('mysql'),
    'updated_at' => current_time('mysql')
), array('%s', '%s', '%s', '%s', '%s'));
24
practice JOIN clause with multiple tables
You need to login to do this manipulation!