oscarotero / simple-crud

PHP library to provide magic CRUD in MySQL/Sqlite databases with zero configuration
MIT License
242 stars 58 forks source link

Warning: strlen() expects parameter 1 to be string, array given #14

Closed elieobeid7 closed 7 years ago

elieobeid7 commented 7 years ago

Here's the code

https://pastebin.com/vpsq9tZ3

The error

Warning: strlen() expects parameter 1 to be string, array given in /opt/lampp/htdocs/web/emall/production/app/vendor/simple-crud/simple-crud/src/Fields/Integer.php on line 35

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category_id' cannot be null in /opt/lampp/htdocs/web/emall/production/app/vendor/simple-crud/simple-crud/src/SimpleCrud.php:230 Stack trace: #0 /opt/lampp/htdocs/web/emall/production/app/vendor/simple-crud/simple-crud/src/SimpleCrud.php(230): PDOStatement->execute(Array) #1 /opt/lampp/htdocs/web/emall/production/app/vendor/simple-crud/simple-crud/src/Queries/Mysql/Insert.php(76): SimpleCrud\SimpleCrud->execute('INSERT INTO `pr...', Array) #2 /opt/lampp/htdocs/web/emall/production/app/vendor/simple-crud/simple-crud/src/Queries/Mysql/Insert.php(58): SimpleCrud\Queries\Mysql\Insert->__invoke() #3 /opt/lampp/htdocs/web/emall/production/app/add_product_ctrl.php(59): SimpleCrud\Queries\Mysql\Insert->run() #4 {main} thrown in /opt/lampp/htdocs/web/emall/production/app/vendor/simple-crud/simple-crud/src/SimpleCrud.php on line 230

As you can see from the code, I haven't used any array, I just followed the readme, unless I'm missing something. Regards

elieobeid7 commented 7 years ago

My database has many foreign keys am i inserting in a wrong field? I really am not inserting arrays, unless $_POST is considered an array

oscarotero commented 7 years ago

select() returns always a RowCollection with 0 or more rows. If you need only one row, use the modifier one():

$cat = $db->category
    ->select()
    ->where('name = :name', [':name' => 'Nike'])
    ->run();

$catId = $cat->id; // array of ids. This is why it fails

$cat = $db->category
    ->select()
    ->one()
    ->where('name = :name', [':name' => 'Nike'])
    ->run();

$catId = $cat->id; // integer with the id

If you don't want to assign the relations manually, this is other option:

//Create a product
$product = $db->product->create([
    'title' => $title,
    'description' => $description,
    'price' => $price,
]);

//Relate with the category
$product->relate($cat);
$product->relate($users);

//Save all in the database
$product->save();
elieobeid7 commented 7 years ago

Man your library is magical. I still have couple of questions thought. Can you use the relate trick to delete? I have one more question, I'll ask it tomorrow if I can't solve the issue

oscarotero commented 7 years ago

You can relate or unrelate data. See the docs:

https://github.com/oscarotero/simple-crud#relate-and-unrelate-data