1

I try different way for insert data in custom table but is not work and there are not errors.

Sometimes is save, but most of the time is not.

I check around the web, but no solution is working for me.

my last method is:

$sql = $wpdb->prepare("INSERT INTO `$table_name` 
(`name`, `email`, `phone`, `address`, `message`, `rq`, `url`) 
values 
(%s, %s, %s, %s, %s, %d, %s)",
$name, $email, $phone, $address, $msg, 1, $url);

$wpdb->query($sql);

I print $sql and paste on phpmyadmin SQL and save it, so the query doesn't have any problem, but still not save.

Why this happen?

I already try with array and $wpdb->insert(), same problem.

EDIT: it is solved. it was an integer passed like string, thanks to everybody

4
  • 1
    Where and how are you running this code? Where are your variables defined? Particularly $table_name. What is the structure of your table? What is the primary key? Commented Jun 26, 2019 at 10:41
  • everything is defined and if I print $sql, copy and paste in phpmyadmin, the query is work. Commented Jun 26, 2019 at 11:00
  • And I am running this code by my own plugin with ajax. It wired that, same inputs sometimes is saving sometimes is not Commented Jun 26, 2019 at 11:06
  • Please add to your question that you're running this after a call to admin-ajax.php. This is an important detail. Commented Jun 26, 2019 at 11:54

1 Answer 1

3

First insert the global.

global $wpdb;

Then You have to check your quotes properly.

$sql = $wpdb->prepare(
    "INSERT INTO `$table_name`      
       (`name`,`email`,`phone`,`message`,`rq`,`url`) 
 values ($name, $email, $phone, $address, $msg, 1, $url)");
$wpdb->query($sql);

OR

$wpdb->insert('$table_name', array(
    'name' => $name,
    'email' => $email,
    'phone' => $phone, // ... and so on
));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.