teleren/devto huggingface dataset:
E3 - Adapting PHP Code to Specify the User
Tags: php, tutorial, sql
Published: 2020-04-14 19:02:33

In the previous examples, you used the root user to connect to your database and the password was an empty string. Now, replace the username and password with the specified username and passwords above.

* Root user - as in previous examples, the user name was "root" and password was an empty string. Any queries by the root user are allowed full access privileges to all your tables.
```php
$databaseLink = new mysqli("localhost", "root", "", "NeatTreats");
```

* Customer user - the username is "Customer" and the password is "CustomerPassword123". Only `SELECT` queries on the product table can be made from this database link.
```php
$customerDatabaseLink = new mysqli("localhost", "Customer", "CustomerPassword123", "NeatTreats");
```


* Admin user - the username is "Admin" and the password is "AdminPassword123". Only `SELECT`, `UPDATE` and `DELETE` queries on the product table can be made from this database link.
```php
$adminDatabaseLink = new mysqli("localhost", "Admin", "AdminPassword123", "NeatTreats");
```


Parent topic: [Example 3](https://dev.to/herobank110/example-3-creating-multiple-database-users-2c97)
E3 - Setting Up Database
Tags: tutorial, sql
Published: 2020-04-14 18:59:35

These are the commands you will need to write into the MySQL console:

1.&nbsp;Delete the database from the previous examples.
```sql
DROP DATABASE NeatTreats;
```

2.&nbsp;Create a database with a product table.
```sql
CREATE DATABASE NeatTreats;
USE NeatTreats;
CREATE TABLE Product (
    ProductID INT,
    Name VARCHAR(125),
    Price FLOAT,
);
```

3.&nbsp;Create the users for your connection (localhost) and choose sensible password.
```sql
CREATE USER Customer@localhost IDENTIFIED BY ‘CustomerPassword123’;
CREATE USER Admin@localhost IDENTIFIED BY ‘AdminPassword123’;
```

4.&nbsp;Assign the query privileges you want each user to have on the product table.
```sql
GRANT SELECT ON Product TO Customer@localhost;
GRANT SELECT, UPDATE, DELETE ON Product TO Admin@localhost;
```


Parent topic: [Example 3](https://dev.to/herobank110/example-3-creating-multiple-database-users-2c97)
Example 3 - Creating Multiple Database Users
Tags: tutorial
Published: 2020-04-14 18:55:27

In this example you will learn how to set up multiple users in your database and specify their access privileges to each of your tables. This example will be relatively short so it won't have an extra steps section. However, you should to apply what you learn to your past and future solutions.

By now, you know how to create a database with multiple tables. But each user should only be able access specific tables. For example, customers need to be able to view the products in stock, but only admins should be able to update the products data. MySQL lets you create users and set their privileges on each of your tables.

Jump to section:
* [Setting Up Database](https://dev.to/herobank110/e3-setting-up-database-2kof)
* [Adapting PHP Code to Specify the User](https://dev.to/herobank110/e3-adapting-php-code-to-specify-the-user-f9l)
E2 - Extra Steps
Tags: tutorial
Published: 2020-04-14 18:43:45

Attempt these steps on your own (with internet research) before consulting my example solution in the next post.

1. Change the form to use the post method and adapt the PHP processing script to make this work.
2. Create a registration success page and redirect the customer there when their record was added successfully.
3. Research input sanitization, particularly SQL injection and cross site scripting attacks and implement preventative measures on the first and last name inputs.
4. Add a check to see if the SQL query returned an error before telling the customer their record was actually added.
5. Instead of a single variable tracking the validation, use an associative array mapping each field to its error, so you know which fields were invalid.
6. You may notice that we made the first name optional but last name required, however the validation check for first name expected the length shorter than 20. Make the validation also pass if the first name is empty.
7. Using CSS, add a colour theme to your page.
8. Using CSS, lay out the form labels and inputs so that each pair shows its label above its input.
9. Move each kind of PHP validation check into a dedicated function so they can be reused. (eg, range, length, pattern, etc).
10. Move all the form processing into a function and then call this function. This is so that local variables are used, which are faster than global variables.
11. Use automatic redirection when the input is invalid instead of outputting a link the user has to click manually.
12. Using the array of validation checks from step 5, send the error messages back to the form page and display the errors next to each input field.
13. Standardise the error messages into constants (eg, `NOT_PRESENT`, `OUT_OF_RANGE`, `INVALID_LENGTH`) and refer to them by name where needed.
14. When the validation fails, prefill the form with the last used values.

Parent topic: [Example 2](https://dev.to/herobank110/example-2-saving-data-from-a-form-4g33)
Respond to multiple content types in Laravel from the same controller
Tags: laravel, php
Published: 2020-04-14 18:37:36

---
title: Respond to multiple content types in Laravel from the same controller
published: true
description: my implementation of rails respond_to in laravel
tags: laravel, php
---

One of the things I really like in rails is [respond_to](https://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to) function. In really simple terms, it allows you to reuse the same controller for different content types. For example if the request is AJAX, you can return a JSON response, otherwise, respond with HTML.

I always wanted this functionality in Laravel, but I did not really like most of the implementations I found online. So I have been using simple early returns:
```php
if ($request->wantsJson()) {
    return [
        'success' => true,
    ];
}

return view('users');
```
This works, but something about it always makes me look for other solutions. Today I decided to give it a try myself and implemented a very simple solution that allows me to write code like this:

```php
Route::get('/', function () {
    return response()
        ->to('html', fn() => view('welcome'))
        ->to('json', fn() => [
            'success' => true,
        ]);
});
```

The best thing about this (and the main difference to other implementations) is that you can return a closure, meaning that the code will only get called if it matches the requested content type. PHP7.4 makes it even better because we can return an arrow function and we don't need to add `use` keyword. So for example if we need to use a request or another variable, we can easily do so:

```php
Route::get('/users', function (Request $request) {
    return response()
        ->to('html', fn() => view('users', [
            'users' => User::all(),
            'query' => $request->get('query'),

        ]))
        ->to('json', fn() => [
            'users' => UserResource::collection(User::all()),
        ]);
});
```

The code for this is [quite simple](https://gist.github.com/dsazup/996cd6ca7f1ff50cc31c0823fe26b2a7) - only around 20 lines. Although it's probably not ready for production use as is, I will be trying this out in my own projects. With some unit tests, I think it would make a really nice composer package. Would this be of interest to anyone? Let me know what do you think :+1:
E2 - Create Database from MySQL Console
Tags: tutorial, sql
Published: 2020-04-14 18:30:47

Open phpMyAdmin (see [Entering SQL commands](https://dev.to/herobank110/getting-started-28el#sql-commands)) and enter these commands:

1.&nbsp;Delete the database from the previous example.
```sql
DROP DATABASE NeatTreats;
```

2.&nbsp;Create the new Neat Treats database.
```sql
CREATE DATABASE NeatTreats;
```

3.&nbsp;Make sure you edit this database going forward.
```sql
USE NeatTreats;
```

4.&nbsp;Create the customer table in the new database. Don't worry about adding too many columns yet. We aren’t going to have preloaded records like the previous example. Instead the records will be inserted whenever a customer registers from the web form.
```sql
CREATE TABLE Customer (
    CustomerID INT,
    FirstName VARCHAR(125),
    LastName VARCHAR(125)
);
```

Parent topic: [Example 2](https://dev.to/herobank110/example-2-saving-data-from-a-form-4g33)
How to Remotely Manage Virtual Teams in 2020
Tags: virtualteams
Published: 2020-04-14 18:29:27

![How to Remotely Manage Virtual Teams](http://perfectial.com/wp-content/uploads/2020/04/How-to-Remotely-Manage-Virtual-Teams-1024x420.jpg)

With new technologies coming to the workspace, remote work is becoming not only manageable but sometimes necessary – as in the recent economic situation caused by the pandemic. An economic recession or even crisis is inevitable and can significantly harm global production, supply chain and have a disruptive financial impact on firms and financial markets.

If you take a look at the economic impact of COVID-19 on China’s economy, you can see that the investment in fixed assets and retail sales are the spheres that suffered the most loss – 24.5% and 20.5%, respectively.

The economies of other countries sadly seem to be following China’s footsteps; some are now delving into an even deeper recession. So, overcoming the COVID-19 impact on the economies is a real challenge for companies now. Therefore, in today’s article, we’re going to explore how remote teams can contribute to your crisis management strategy and help keep your workflows going with minimum loss.

![Remote Teams-The economies of other countries](http://perfectial.com/wp-content/uploads/2020/04/Remote-Teams-The-economies of other-countries-1024x782.jpg)

The post [How to Remotely Manage Virtual Teams in 2020](https://perfectial.com/blog/remotely-manage-virtual-teams/) appeared first on [IT Consulting Company Perfectial](https://perfectial.com/).
Using Pull Requests to Review Data like Code
Tags: git, sql, database
Published: 2020-04-14 18:27:22

[Dolt](https://github.com/liquidata-inc/dolt) is a SQL database with built-in Git versioning, branching, and distribution semantics that makes collaborating on and distributing data effortless.

[DoltHub](https://www.dolthub.com/) is a place to share Dolt repositories.   Similar to how you can use pull requests on GitHub to discuss and review potential code changes with collaborators before merging into the base branch, we used pull requests on DoltHub to build a collaborative state response dataset for COVID-19. 

Want to know more? [Read about how to use pull requests to review and improve data in this blog.](https://www.dolthub.com/blog/2020-04-13-corona-virus-state-actions-using-pull-requests/)

You can also take a look at the public coronavirus state response dataset [here](https://www.dolthub.com/repositories/Liquidata/corona-virus-state-action).
Example 2 - Saving Data From a Form
Published: 2020-04-14 18:25:38

In this example you will learn how to process inputs from a web form and save it in the database. There will be 3 stages, followed by extra steps and a sample solution.

Jump to section:
* [Create Database from MySQL Console](https://dev.to/herobank110/create-database-from-mysql-console-4h49)
* [Creating the Web Form](https://dev.to/herobank110/e2-creating-the-web-form-1bdd)
* [Processing the Form](https://dev.to/herobank110/e2-processing-the-form-5gjk)
* [Extra Steps](https://dev.to/herobank110/e2-extra-steps-23o7)
* [Sample Solution](https://dev.to/herobank110/e2-sample-solution-3mpc)
E1 - Sample Solution
Tags: php, tutorial
Published: 2020-04-14 18:21:27

You will learn the most from this tutorial if you attempt to follow the [extra steps](https://dev.to/herobank110/e1-extra-steps-3229) on your own before checking this sample solution.

```php
<?php
 
/**
 * Returns the welcome message associated with a message ID.
 * 
 * This message is shown to the user when they first access the index
 * page. It is meant as a welcoming message and can be personalised for
 * each user.
 *
 * When writing documentation comments, start with a single line brief
 * description, and if necessary provide additional details below.
 * You should always document each parameter and the return value of
 * a function unless it is an extremely simple function.
 *
 * @param integer $messageId ID of the message to select.
 * @param mysqli $databaseLink Connection to database to query with.
 * Must have SELECT access to the WelcomeMessage table.
 * @return string Welcome message from the database. Empty string is
 * returned if $messageId wasn't found in the database.
 */
function getWelcomeMessage(int $messageId, mysqli $databaseLink): string
{
    $result = $databaseLink->query(
        "SELECT Message FROM WelcomeMessage WHERE MessageID = $messageId;"
    );
 
    if (!empty($databaseLink->error) || $result->num_rows() == 0) {
        // An error occurred during the query or there were no matching records.
        // Return empty string.
        return "";
    }
 
    return $result->fetch_assoc()["Message"];
}
?>
 
<html><body><?php
// Output the message to the user as HTML output.
$databaseLink = new mysqli("localhost", "root", "", "NeatTreats");
echo getWelcomeMessage(1, $databaseLink);
$databaseLink->close();
?></body></html>
```

Parent topic: [Example 1](https://dev.to/herobank110/example-1-getting-data-from-database-516f)
E1 - Extra steps
Published: 2020-04-14 18:17:55

How can you improve the code we made in the previous two stages? Here are some ideas to get you started. Search the internet if you are stuck. Then check against my solution to the extra steps (see next page).

1. Add comments explaining each line.

2. Put all the PHP code into a function with a sensible name and call it where needed.

3. Move the function definition above the first `html` element, but call it from the body. (use multiple PHP elements).

4. Replace the `MessageID` comparison value in the query with a function parameter and use variable substitution to formulate the query before it is sent.

5. Initialise `$databaseLink` outside the function and pass it to your function via a function parameter. (You will be able to reuse it across different functions before closing).

6. Make the function return the value instead of echoing it. Then, echo the value when you call the function. (Sometimes it may be beneficial to further manipulate function outputs rather than echoing the results to the user straight away).

7. Add a check to see if the query caused an error or returned empty before fetching the row. Make the function return a different value in this case, like an empty string.

8. Specify the data types for the parameters and return value of your function in the function signature. (remember, databaseLink is a mysqli object)

9. Add a documentation block to your function explaining its purpose, parameters and return value.

Parent topic: [Example 1](https://dev.to/herobank110/example-1-getting-data-from-database-516f)
Material UI, React Router boilerplate.
Tags: react, uiweekly, webdev, javascript
Published: 2020-04-14 18:16:19

TL;DR
[Link](https://github.com/Rohithgilla12/react-router-material-boilerplate/) for the GitHub repository.

 Many developers including me feel bored doing some routine stuff ordinarily whenever we set up a project. That's where boilerplates come to the rescue.

So I personally use [Material UI](https://github.com/mui-org/material-ui/) for the components and icons and [React Router](https://github.com/ReactTraining/react-router) for routing in react applications. I felt building a boilerplate template for this would benefit quite a few developers.

So I developed [this](https://github.com/Rohithgilla12/react-router-material-boilerplate/). You can click on the `Use this template` button on the GitHub. It asks for the repository name and `Et Voila` your react app with `react-router`, `material-ui` and `material-icons`.

Feel free to fork the repo, create issues, make PRs.

Peace ✌🏻
Rohith Gilla
Enable fullscreen view on nativescript-vue
Tags: nativescriptvue, nativescript, snippet
Published: 2020-04-14 18:15:32

---
title: Enable fullscreen view on nativescript-vue
published: true
description: 
tags: nativescript-vue, nativescript, snippet
---

```js
import * as app from 'tns-core-modules/application'
import { device } from 'tns-core-modules/platform'

export function hideSystemUi () {
  if (!app.android || parseInt(device.sdkVersion) < 21) { return }
  const androidViewPkg = android.view // eslint-disable-line no-undef
  const window = app.android.startActivity.getWindow()
  window.addFlags(androidViewPkg.WindowManager.LayoutParams.FLAG_FULLSCREEN)
  window.clearFlags(androidViewPkg.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)
}

export function showSystemUi () {
  if (!app.android || parseInt(device.sdkVersion) < 21) { return }
  const androidViewPkg = android.view // eslint-disable-line no-undef
  const window = app.android.startActivity.getWindow()
  window.addFlags(androidViewPkg.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)
  window.clearFlags(androidViewPkg.WindowManager.LayoutParams.FLAG_FULLSCREEN)
}

```
E1 - Creating a PHP page that interacts with the database
Tags: php, tutorial
Published: 2020-04-14 18:14:53

Before starting this example, you must have completed the [Create a database](https://dev.to/herobank110/e1-creating-database-from-mysql-console-3iie) stage.

Create a file called `index.php` (see [Create project folder](https://dev.to/herobank110/getting-started-28el#proj-folder)) and follow these steps:

1. Add an HTML html element and a body inside it. ```html
<html><body></body></html>
```

2. Add a PHP element to your body. ```php
<?php ?>
```

3. Connect to your database as the root user, use a query to get the message from the row just added, then close the connection. ```php
$databaseLink = new mysqli("localhost", "root", "", "NeatTreats");
$result = $databaseLink->query("SELECT Message FROM WelcomeMessage WHERE MessageID = 1;");
```

4. Echo the data so you can see it on the HTML page, then close the database connection. ```php
echo $result->fetch_assoc()["Message"];
$databaseLink->close();
```

The final code should look as follows. Test the file in your browser to get a message from the database.
```php
<html><body><?php
$databaseLink = new mysqli("localhost", "root", "", "NeatTreats");
$result = $databaseLink->query("SELECT Message FROM WelcomeMessage WHERE MessageID = 1;");
echo $result->fetch_assoc()["Message"];
$databaseLink->close();
?></body></html>
```

Parent topic: [Example 1](https://dev.to/herobank110/example-1-getting-data-from-database-516f)
Automated testing in a build pipeline
Tags: testing, docker, bash, basics
Published: 2020-04-14 18:08:03

A testing [mindset](https://www.tegh.net/knowledge/testing-is-a-mindset/) with its' [scripts](https://www.tegh.net/knowledge/bashing-tests/) would be incomplete if we did not put them to good use.

Ideally, tests should be run every time we intend to share our code with anyone - be it our team or the whole world.
It is a tech lead's wet dream to work in an environment where every dev thoroughly tests their solutions. 
As this might be impossible, we can have the next best thing. 

We can make tests run automatically every time new or modified code is introduced into the codebase.

Let's assume we do everything in _Docker_ and any new code is built by a server that prevents merging changes until a new _image_ is successfully created.

We'll use the `tests.sh` from [before](https://www.tegh.net/knowledge/bashing-tests/) and add a `test_scenario.sh` which checks if all the use cases we need are covered.

```bash
# When we run the script:
bash test_scenario.sh

# We get:
Test #1: PASS
Test #2: PASS
Test #3: PASS
Test #4: PASS
Test #5: PASS
Test #6: PASS
Test #7: PASS
```

Now, we can create a `Dockerfile` that will use the above script to check if our app is behaving properly.

```Dockerfile
FROM bash
COPY test*.sh ./

RUN bash test_scenario.sh
```

The docker image described above will not be built if the tests fail. Like this:
```bash
# Try to build the image
docker build .

# We get:

Sending build context to Docker daemon  4.608kB
Step 1/3 : FROM bash
 ---> 78664daf24f4
Step 2/3 : COPY test*.sh ./
 ---> fe75cddc7f0f
Step 3/3 : RUN bash test_scenario.sh
 ---> Running in 010702b02aea
Test #1: PASS
Test #2: PASS
Test #3: PASS
Test #4: PASS
Test #5: PASS
Test #6: PASS
Test #7: FAIL
The command '/bin/sh -c bash test_scenario.sh' returned a non-zero code: 1
```

With this approach, there will never exist a runnable version of our app that did not pass all the required tests.
When we fix the app, the test will work again.

```bash
# [...]
Step 3/3 : RUN bash test_scenario.sh
 ---> Running in c2d555481c28
Test #1: PASS
Test #2: PASS
Test #3: PASS
Test #4: PASS
Test #5: PASS
Test #6: PASS
Test #7: PASS
Removing intermediate container c2d555481c28
 ---> d41d9ecb5ed9
Successfully built d41d9ecb5ed9
```

... and we will have a new image built and ready to use.

Of course, there are different types of tests. Some of them will not be able to run before the application is actually built and deployed to a testing environment.
Real-life requires more sophisticated configurations, but the general idea is here.

> Both `*.sh` files and the `Dockerfile` are available on [GitHub](https://github.com/teghnet/www/tree/master/src/testing).
E1 - Creating database from MySQL console
Tags: php, tutorial
Published: 2020-04-14 18:07:40

Open phpMyAdmin (see Getting Started) and enter these commands:

1. Create the Neat Treats database. ```sql
CREATE DATABASE NeatTreats;
```

2. Make sure you edit this database going forward. ```sql
USE NeatTreats;
```

3. Create the welcome message table in the new database. Don't worry about relationships yet. ```sql
CREATE TABLE WelcomeMessage (
    MessageID INT,
    Message VARCHAR(255)
);
```

4. Insert a row into the table. Make sure to use `'` single quote rather than `"` double. ```sql
INSERT INTO
    WelcomeMessage (MessageID, Message)
VALUES
    (1, 'Welcome');
```

Parent topic: [Example 1](https://dev.to/herobank110/example-1-getting-data-from-database-516f)
Example 1 - Getting Data From Database
Tags: php, tutorial, database
Published: 2020-04-14 18:06:18

In this example you will learn how to load data into a database and present it on a web page.

Jump to section:
* [Creating database from MySQL console](https://dev.to/herobank110/e1-creating-database-from-mysql-console-3iie)
* [Creating a PHP that interacts with the database](https://dev.to/herobank110/e1-creating-a-php-that-interacts-with-the-database-3mb6)
* [Extra steps](https://dev.to/herobank110/e1-extra-steps-3229)
* [Sample solution](https://dev.to/herobank110/e1-sample-solution-1bpj)
Introduction to Examples
Published: 2020-04-14 17:59:26

In the following posts, I will run through some examples of PHP and MySQL that start easy until we work up to a complex multi-file example. Along the way, I will provide step by step instructions and the previous PHP resources are available if you get lost.

The structure of each example will be as follows:
* description of the problem to be solved
* walkthrough of using PHP and MySQL to solve the problem
* extra steps for you to attempt to extend your solution
* example solution to the extra steps

Note: The sample solutions will contain a copy of my solution in each post, although the solutions are also available on [my Github](https://github.com/herobank110/PHP-Tutorial).

Now, let's get started!