Chuck Grimmett

  • How to Back Up Your Laravel Homestead Databases

    Today I upgraded from Homestead 4.0.0 to 5.0.1 so I could test my sites in PHP 7. That was a major upgrade and a number of things changed, so I decided that I needed to back up my databases before I did the upgrade. I’d only ever dumped specific databases before, but TIL how to dump them all at once. Here is how to do that in Laravel Homestead:

    1. $ cd ~/Homestead
    2. $ vagrant ssh
    3. $ mysqldump -u homestead -psecret --all-databases > Code/homestead-YYYY-MM-DD-hh-mm.sql
    4. Test the sql file. I had a syntax error the first time and it only wrote out an error message. You’ve been warned.
    5. Move the SQL file somewhere safe. IE outside of any folder you might delete or change during the upgrade.
    6. After the upgrade, here is how to reload your databases in Homestead: $ mysql -u homestead -psecret < Code/homestead-YYYY-MM-DD-hh-mm.sql

    I had some major issues with the upgrade. When I first tried it, vagrant up hung at the SSH auth step and never moved. I went down a deep rabbit hole with my friend Eric Davis trying to debug the SSH issues, to no avail. My last trial was to roll back to Homestead 4.0.0, check my vagrant ssh-config settings, then try the upgrade with those settings. Then, miraculously, when I tried the upgrade again, vagrant up worked with no SSH problems! No difference in settings. I’m baffled, but relieved.

    FYI, there are some Homestead.yaml differences between Homestead 4 and 5, so make sure you have some time set aside to read the docs, update your yaml file, and rerun vagrant up --provision a bunch of times to get everything working again.

  • Bulk Clearing Expiration Dates in Restrict Content Pro

    Bulk Clearing Expiration Dates in Restrict Content Pro

    At Praxis we use Restrict Content Pro as the membership system for our curriculum portal. We decided that all grads get access for life, not just during the program. So, I needed a way to clear over 200 member expiration dates. The only bulk method available through the WordPress interface is to set the expiration dates to another date in the future, which would just kick my problem further down the road. So I needed to dust off my SQL knowledge and directly edit the database.

    Step 1: Back up the database.

    Don’t be a fool. Back up your database and test the queries on a local development version first. Never run queries for the first time on production. The backup is also a failsafe that you can restore if something goes wrong despite your testing.

    Step 2: Find the data.

    I saw that all data related to Restrict Content Pro usually had rcp somewhere in the table, column, or key. So I started with the rcp tables. They had nothing to do with expiration dates, so I checked the wp_usermeta table since RCP extends the WordPress users with more functionality. Bingo. There was a column called meta_key with rcp_expiration in it with corresponding date values.

    Step 3: Make sure you are editing the correct data by running a SELECT statement first.

    Sure, you could run your UPDATE statement first, but I like to make sure I am editing the correct data by running a SELECT statement first and then using the same WHERE clause for my UPDATE statement.

    After a few stupid syntax errors, here is the SELECT statement that got exactly what I wanted. This shows the user ID so I can spot check, restricts searching to the rcp_expiration meta key, and looks for values that are not none.

    SELECT user_id, meta_key, meta_value FROM wp_usermeta WHERE meta_key = 'rcp_expiration' AND meta_value != 'none';

    This returned 176 results. When I changed it to show only meta values that were none, I got 31 values. 31+176=207, which is the total number of users. Looking good.

    Step 4: Craft your UPDATE statement.

    Now that we know we selected the correct data with our previous statement, it is time to craft our UPDATE statement.

    Here I’m updating the wp_usermeta table and setting the meta_value to none where the meta_key is rcp_expiration and the corresponding meta_value is not none.

    UPDATE wp_usermeta SET meta_value = 'none' WHERE meta_key = 'rcp_expiration' AND meta_value != 'none';

    I tested this on my local machine and it updated 176 rows. Just like we wanted.

    Step 5: Run the same query on production.

    Now that we’ve tested the query in our development environment and verified that we got the results we wanted, we can run the query on the production database. If you use phpmyadmin and want to triple check that you aren’t messing anything up, you can click the “Simulate Query” button first. (I did.)

    Step 6: Verify things worked.

    Log in to WordPress and check the RCP membership area. Verify that all expiration dates are now set to none. Also verify that your users can still log in. You should have a few user test logins specifically for this purpose. You can also check your site logs throughout the day to make sure people are still logging in. You can’t count on them always letting you know when something doesn’t work. More often than not they will just stop using it. It is up to you to verify everything works as it should!

  • Many-to-Many Relationships in Relational Data Models

    Many-to-Many Relationships in Relational Data Models

    Today I learned about Many-to-Many relationships in relational data models

    • A many-to-many relationship is a type of cardinality that refers to the relationship between two entities A and B in which A may contain a parent instance for which there are many children in B and vice versa.
    • For example, a recipe may have many ingredients and a specific ingredient may be used in many recipes.
    • In SQL, this relationship is handled by an associative table. The primary key for this type of table is composed of two different columns, both of which reference columns in other tables that you are associating together.
    • It is a good convention to name these associative tables by how they reference each other: Table1_Table2
    • A SELECT statement on an associative table usually involves JOINing the main table with the associative table.
    • If you don’t want to run these JOINs every time, create a view first. A view is a virtual table based on the result-set of an SQL statement. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.

    Example SQL for creating an associative table:

    CREATE TABLE recipes_ingredients (     RecipeID INT(11) REFERENCES Recipes (RecipeID),     IngredientID INT(11) REFERENCES Ingredients (IngredientID),     PRIMARY KEY (RecipeID, IngredientID) )
  • Excel formulas to combine columns and convert time, More SQL functions

    Excel formulas to combine columns and convert time, More SQL functions

    Today I learned:

    Excel Formula to Combine Columns

    =[@Column1] & [@Column2]

    For example: here is how I’d combine columns of hours and minutes and put a colon in-between: =[@Hour] & ":" & [@Minute]


    Convert hours.minutes to hh:mm:ss in Excel

    Take 275.75 and convert it to 275:45 =CELL/24 converts the hours.minutes to days Then you format the column by Custom > Time > 37:30:55 (hh:mm:ss)


    SQL Dates, Concatenation, and Grouping

    I learned some useful things today in SQL: SUM(), CONCAT_WS() to get CSV output, DATE() to get the date part of a datetime stamp, and GROUP BY to get the sums grouped by another column

    SELECT SUM(calls), username  FROM scoreboard_calls GROUP BY username;  SELECT DATE(time), SUM(calls) FROM scoreboard_calls GROUP BY DATE(time);  SELECT CONCAT_WS(',',SUM(calls),username) "calls,user" FROM scoreboard_calls GROUP BY username ORDER BY username, SUM(calls);
  • Aliases in SQL and Sorting Tables with jQuery

    Aliases in SQL and Sorting Tables with jQuery

    Today I learned:

    Aliases for Tables in SQL

    In your FROM statements, you can give tables temporary aliases to make them easier to refer to throughout the rest of the query using AS:

    SELECT o.OrderID, o.Total, m.MemberName FROM Members AS m, Orders AS o WHERE m.MemberName="John Smith" AND m.MemberID=o.MemberID ORDER BY o.OrderID;

    Sorting tables with jQuery

    This Tablesorter jQuery plugin is nifty. It make sorting tables on the fly quick and easy. Tablesorter.com lays out all of the specs.

    Lay out your table with

    and

    tags, then tell tablesorter where to find your table:

    $(document).ready(function()      {          $("#myTable").tablesorter();      }  ); 

    See it in action:

    ID Name Age Skill
    1 Jessica 31 SQL
    2 Frank 68 TCL
    3 Jason 12 jQuery
    4 Tim 43 PHP

  • Hiding Categories from the Jekyll Paginator, Unless, and Insert statements

    Hiding Categories from the Jekyll Paginator, Unless, and Insert statements

    Today I learned:

    Hiding Categories from Paginator

    According to the Jekyll docs, the jekyll-paginator plugin does not support categories or tags. That means there is no way to exclude a category as a whole. You can only exclude posts individually by including hidden: true in each post’s YAML front-matter.

    I’m hiding all of my TIL posts from the front page of my site, so I did a global find and replace to accomplish it.

    Mirror of If statement in Liquid

    Liquid has a neat concept that is the inverse of an If statement. It executes if a condition is not met.

    {% unless post.categories contains 'TIL' %} 	Code here to display all the things! {% endunless %}

    Inserting via mysqli()

    Using the mysqli() function I wrote about yesterday, here is how to insert something into a table:

     $connect = new mysqli($server, $db_username, $password, $db); $connect->query("INSERT INTO `table_name` (username) VALUES ('$user');");

    Make sure your variables are sanitized first! You don’t want someone doing a SQL injection.

    Eric Davis told me that mysqli() is the old way of doing things and I should check out PDO instead.

  • Connecting and Writing to MySQL with PHP

    Connecting and Writing to MySQL with PHP

    Today I learned:

    Connecting to MySQL with PHP

     $server = "localhost"; $username = "username"; $password = "password"; $db = "dbname";  //connect $connect = new mysqli($server, $username, $password, $db);  //Check Connection if ($connect->connect_error) { 	die("The connection failed: " . $connect->connect_error); }

    Check if a table exists and create it if not

    This checks for a table called scorecard_test and creates it if it doesn’t exist. The SQL parameters for the columns are:

    • An integer called ID that is the primary key and auto increments
    • A username that can’t be NULL
    • A column called counter that has a default value of 1 if there is nothing passed, and the length can’t be longer than one digit
    • A column that holds the current timestamp.
     // SQL syntax $sql = "CREATE TABLE IF NOT EXISTS scorecard_test ( id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, username varchar(255) NOT NULL, counter int(1) NOT NULL DEFAULT 1, time TIMESTAMP )";  // Connecting, sending query, showing errors, and closing connection if ($connect->query($sql) === TRUE) { 	echo "Done!"; } else { 	echo "Error: " . $connect->error; }  $connect->close();