Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Store Arrays In MYSQL With PHP

INTRODUCTION
HAVING TROUBLE?

Welcome to a tutorial on how to store arrays in MYSQL with PHP. So you have defined an array in PHP and want to store them into the database? Well, the short answer is you can’t do it directly.

But you can Json Encode the array into a flat string, then store it into the database. But then again, JSON encoded strings are not really the best solutions… So in this guide, we will walk through 2 different ways to Store Arrays into the database, and when to use each method. Read on!

I have included a zip file with all the source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

   

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
JSON Encode Decode

Section B
Separate Table

Extra
Download & More

Closing
What’s Next?

 

  

SECTION A
JSON ENCODE DECODE

We cannot store arrays into the database directly, but we can store flat strings. That is exactly what we will do with this method, to store a JSON encoded string, then retrieve the array back with JSON decode. 

THE DATABASE TABLE

In this example, we will be creating a simple people table and their favorite colors.

sql-people.sql
CREATE TABLE `people` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `fav_color` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `people`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `email` (`email`),
  ADD KEY `name` (`name`);

ALTER TABLE `people`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
FieldDescription
idPerson ID, primary key.
nameThe person’s name.
emailThe person’s email, unique.
fav_colorThe person’s favorite colors.

THE CONFIG FILE

lib/config.php

Next, we create a config file to store all the settings and stuff – Please remember to change the database settings to your own.


 

DATABASE LIBRARY

lib/lib-database.php
pdo = new PDO(
        $str, DB_USER, DB_PASSWORD, [
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
          PDO::ATTR_EMULATE_PREPARES => false
        ]
      );
      return true;
    }

    // ERROR - DO SOMETHING HERE
    // THROW ERROR MESSAGE OR SOMETHING
    catch (Exception $ex) {
      print_r($ex);
      die();
    }
  }

  function __destruct() {
  // __destruct() : close connection when done

    if ($this->stmt !== null) { $this->stmt = null; }
    if ($this->pdo !== null) { $this->pdo = null; }
  }

  function start() {
  // start() : auto-commit off

    $this->pdo->beginTransaction();
  }

  function end($commit=1) {
  // end() : commit or roll back?

    if ($commit) { $this->pdo->commit(); }
    else { $this->pdo->rollBack(); }
  }

  function exec($sql, $data=null) {
  // exec() : run insert, replace, update, delete query
  // PARAM $sql : SQL query
  //       $data : array of data

    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($data);
      $this->lastID = $this->pdo->lastInsertId();
    } catch (Exception $ex) {
      $this->error = $ex;
      return false;
    }
    $this->stmt = null;
    return true;
  }

  function fetch($sql, $cond=null, $key=null, $value=null, $col=null) {
  // fetch() : perform select query
  // PARAM $sql : SQL query
  //       $cond : array of conditions
  //       $key : sort in this $key=>data order, optional
  //       $value : $key must be provided, sort in $key=>$value order
  //       $col : get a "flat" array with data from this column

    $result = false;
    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($cond);
      if (isset($key)) {
        $result = array();
        if (isset($value)) {
          while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
            $result[$row[$key]] = $row[$value];
          }
        } else {
          while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
            $result[$row[$key]] = $row;
          }
        }
      } else if (isset($col)) {
        while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
          $result[] = $row[$col];
        }
      } else {
        $result = $this->stmt->fetchAll();
      }
    } catch (Exception $ex) {
      $this->error = $ex;
      return false;
    }
    $this->stmt = null;
    return $result;
  }
}
?>

Moving on, we create a database library, so we don’t have to repeat the same pieces of database code…

FunctionDescription
__constructConstructor, automatically connects to the database when the object is created.
__destructDestructor, automatically closes database connection when the object is destroyed.
startAuto commit off. Used in conjunction with end.
endTo commit or rollback. Used in conjunction with start.
execRun insert, replace, update, or delete query.
fetchRun a select query.

STORING DATA

JSON-store.php
exec($sql, $data) ? "OK" : $libDB->error;

Now that we have all the groundworks ready, all that is left is to write the SQL and push the data in – Take note that we use json_encode here to “convert” the array into a string.

RETRIEVING DATA

JSON-retrieve.php
fetch($sql, ["[email protected]"]);

// THE RETRIEVED PERSON
if (count($person)==1) {
  $person = $person[0];
  print_r($person);
  echo "


"; // We can get back the favorite colors with JSON decode $colors = json_decode($person['fav_color']); print_r($colors); }

To retrieve the array back, we simply do the opposite of using json_decode.

SECTION B
SEPARATE TABLE

Using a JSON encoded string is all cool, but it has some shortcomings. So let us walk through an alternative here.

THE DATABASE TABLE

sql-fav-color.sql
CREATE TABLE `fav_color` (
  `id` int(11) NOT NULL,
  `color` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `fav_color`
  ADD PRIMARY KEY (`id`,`color`);
FieldDescription
idPerson ID, partial primary key.
colorColor name, partial primary key.

Yep, we are creating another table here to hold the favorite colors one-by-one.

 

STORING DATA

alt-store.php
start();

// CREATE MAIN ENTRY FIRST
$sql = "INSERT INTO `people` (`name`, `email`) VALUES (?, ?)";
$data = [$name, $email];
$pass = $libDB->exec($sql, $data);

// CREATE COLOR ENTRIES
if ($pass) {
  $id = $libDB->lastID;
  $sql = "INSERT INTO `fav_color` (`id`, `color`) VALUES ";
  $data = [];
  foreach ($colors as $c) {
    $sql .= "(?, ?),";
    $data[] = $id;
    $data[] = $c;
  }
  $sql = substr($sql, 0, -1) . ";";
  $pass = $libDB->exec($sql, $data);
}

// END - COMMIT OR ROLLBACK
$libDB->end($pass);
echo $pass ? "OK" : $libDB->error ;

Storing the data becomes a little more tedious now, but we can simply loop through the array to create the entries and the SQL.

RETRIEVING THE ARRAY

alt-retrieve.php
fetch($sql, ["[email protected]"]);

// THE RETRIEVED PERSON
if (count($person)==1) {
  $person = $person[0];
  print_r($person);
  echo "


"; // GET FAVORITE COLORS $sql = "SELECT * FROM `fav_color` WHERE `id`=?"; $colors = $libDB->fetch($sql, [$person['id']], null, null, "color"); print_r($colors); }

There is no need for any decoding here – Just pull all the data back out from the database.

WHY THIS METHOD MAKES SENSE

Some of you guys may be thinking that this method is totally dumb, roundabout, and wastes more system resources. Well, no, and let us walk through why this method is preferred in most cases. Let us create some more dummy data entries first.

alt-dummy.php
 "Joe Doe", "email" => "[email protected]", "col" => ["red", "blue"]],
    ["name" => "Jin Doe", "email" => "[email protected]", "col" => ["blue", "cyan"]],
    ["name" => "Jon Doe", "email" => "[email protected]", "col" => ["yellow", "blue"]],
    ["name" => "Jen Doe", "email" => "[email protected]", "col" => ["blue", "magenta"]],
    ["name" => "Jan Doe", "email" => "[email protected]", "col" => ["cyan", "yellow"]]
];

// DATABASE ACTION
$libDB->start();
foreach ($people as $p) {
  $sql = "INSERT INTO `people` (`name`, `email`) VALUES (?, ?)";
  $data = [$p['name'], $p['email']];
  $pass = $libDB->exec($sql, $data);
  if ($pass) {
    $id = $libDB->lastID;
    $sql = "INSERT INTO `fav_color` (`id`, `color`) VALUES ";
    $data = [];
    foreach ($p['col'] as $c) {
      $sql .= "(?, ?),";
      $data[] = $id;
      $data[] = $c;
    }
    $sql = substr($sql, 0, -1) . ";";
    $pass = $libDB->exec($sql, $data);
  }
}
$libDB->end($pass);
echo $pass ? "OK" : $libDB->error ;
echo "

";

With that, let us now do some data mining and find out which are the most and least common favorite colors.

alt-stats.php
fetch($sql, null, "color", "count");
print_r($data);

For those of you who don’t catch the drift – It is impossible or very difficult to do this with JSON encoded strings. The value of creating a separate table is not in the convenience of coding, but the power to do data analysis. So always weigh your pro and cons carefully, that laziness to cut a few lines of code comes at the cost of losing the ability to do proper studies.

EXTRA
DOWNLOAD & MORE

That’s all for the code, and here is the download link as promised – Plus a small extra that may be useful to you.

JSON

Just what the heck is JSON? Find out in my other guide.

Simple PHP JSON For Beginners (Examples and Tutorial)

SOURCE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
  

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped to solve your problems, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post How to Store Arrays In MYSQL With PHP appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

How to Store Arrays In MYSQL With PHP

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×