B
B
bwylla2020-08-06 22:52:17
PHP
bwylla, 2020-08-06 22:52:17

Why is JSON not saved to the database?

#Order.php

class Order
{
  public static function save($name, $email, $phone, $userId, $comments, $products)
  {
    $db = Db::getConnection();

    $products = json_encode($products);
    echo $products;

    $sql = 'INSERT INTO orders (name, email, phone, user_id, comments, products ) '
                	. 'VALUES (:name, :email, :phone, :user_id, :comments, :products)';
         
    $result = $db->prepare($sql);
    $result->bindParam(':name', $name, PDO::PARAM_STR);
    $result->bindParam(':email', $email, PDO::PARAM_STR);
    $result->bindParam(':phone', $phone, PDO::PARAM_STR);
    $result->bindParam(':user_id', $userId, PDO::PARAM_STR);
    $result->bindParam(':comments', $comments, PDO::PARAM_STR);
               //Если вместо $products поставить к примеру переменную $id равную 1,
                  то запись сохраняется
    $result->bindParam(':products', $products, PDO::PARAM_STR);


    return $result->execute();
  }
}


#CartController.php

if (isset($_POST['order_btn'])) {
  $phone = $_POST['phone'];
  $address = $_POST['address'];
  $name = $_POST['name'];
  $email = $_POST['email'];
  $comments = $_POST['comments'];

  $errors = false;

  if (!User::checkPhone($phone)) {
    $errors[] = 'Invalid phone';
  }

  if (!User::checkName($name)) {
    $errors[] = 'Invalid Name';
  }

  if (!User::checkEmail($email)) {
    $errors[] = 'Invalid Email';
  }

  if ( $errors == false ) {
    $productsInCart = Cart::getProducts();
          
    if ( User::isGuest() ) {
      $userId = false;				
    } else {
      $userId = User::checkLogged();
    }

    $result = Order::save($name, $email, $phone, $userId, $comments, $productsInCart);
    if ( $result ) {
      Cart::clear();
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SKEPTIC, 2020-08-06
@bwylla

What is the field size? Does it contain your meaning?
Try the TEXT field type, where you want to store the products in the database.

T
ThunderCat, 2020-08-06
@ThunderCat

Look for errors in the logs
Check the contents of variables
Check the request with your hands from the console or from phpmyadmin
Think with your head

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question