aung aye
aung aye

Reputation: 45

insert_record(); Error writing to database

I created new table in moodle by phpmyadmin. Now I want to insert data into new table "dev". I got Error writing to database. my code is...

if($_POST['send']){
    $id =$_POST['id'];
    $name =$_POST['name'];
    global $DB;
    $data = new stdClass();
    $data->dev_id  = $id;
    $data->dev_name = $name;
    $DB->insert_record('dev', $data);

Upvotes: 2

Views: 1876

Answers (2)

igorshmigor
igorshmigor

Reputation: 802

There are different possibilities. It's hard to tell without knowing the database structure and the data contained inside.

1: The table doesn't exist. As Russell England said, make sure the table mdl_dev exists.

2: The table has some required fields that you didn't assign to your $data-Object and there's no default defined.

3: One of the fields is unique and the value that you've passed to your $data-object for that field is already used in the table by a different data set.

4: The data types that you pass to the table don't match the type that's defined for your table field, such as trying to save a string in an INT field.

5: Your values exceed the allowed range, such as the name being longer than the defined maximum length for that field.

Upvotes: 0

Russell England
Russell England

Reputation: 10241

Quick answer:

Is the dev table called mdl_dev?

Long answer:

Switch on debugging during development, this will give you a more detailed error message:

https://docs.moodle.org/30/en/Debugging

In your config.php add this:

// Developer settings - not for production or staging!
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 0);

$CFG->debug = E_ALL | E_STRICT; // 32767;
$CFG->debugdisplay = true;

Also, you should use the XMLDB editor for creating tables :

https://docs.moodle.org/dev/XMLDB_editor

Also never user $_POST directly, this can introduce SQL injection. Always use optional_param() or required_param() - for example:

$send = optional_param('send', false, PARAM_BOOL);
$id = optional_param('id', null, PARAM_INT);
$name = optional_param('name', null, PARAM_TEXT);
if ($send) {
    ...

Upvotes: 2

Related Questions