Hello, Programmers!

Basic CRUD Operations for Demanding Programs

Alter PHP versions UBUNTU

Check and Set installed PHP versions

  
    $ sudo update-alternatives --list php
    $ sudo update-alternatives --config php
  
  

Alter PHP version


Apache:
$ sudo a2dismod php7.4
$ sudo a2enmod php8.3
$ sudo service apache2 restart

Command Line:
$ sudo update-alternatives --set php /usr/bin/php5.6

  

Enabling mod_rewrite (.htaccess) Apache2


$ sudo a2enmod rewrite
$ sudo systemctl restart apache2
-> Then open: sudo nano /etc/apache2/sites-available/000-default.conf
-> Change:  
      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted
      

  

Laravel CRUD Auth

Target Version: Laravel Create Porject

 
$ composer create-project --prefer-dist laravel/laravel crudapplication "6.*"

Laravel Create Porject With Latest Version

 
$ composer create-project laravel/laravel crudapplication

Laravel Auth Implement

 
$ composer require laravel/ui
  
$ php artisan ui bootstrap --auth 

NPM Implement

 
$ npm install 
  
$ npm run dev

$ php artisan migrate

$ npm run build
  

Create Migration Table

 
$ php artisan make:migration create_contacts_table --create=Table_NAME 

Migrate Tables To Database

 
$ php artisan migrate

Create Model

 
  $ php artisan make:model Contact

Create Controller

 
$ php artisan make:controller ContactController --resource--model=Contact

Route Controller

 
  $ Route::resource(‘/contact’,'App\Http\Controllers\ContactController'); 

Run Development Server

 
$ php artisan serve
$ php artisan serve --host 192.168.89.83 --port 8080

Error Handler

Run this if clone somewhere project

 
$ composer install  
$ composer update --ignore-platform-reqs
$ composer dump-autoload
$ composer update --no-scripts
$ composer dump-autoload -o

Optimize, Clear Cache and Config

 
$ php artisan optimize:clear
$ php artisan cache:clear
$ php artisan config:clear

Database Migrate + Model Relationship

SINGLE FILE MIGRATE

 
$ php artisan migrate  
$ php artisan migrate --path=/database/migrations/2014_users_table.php #new created single file
$ php artisan migrate:refresh --path=/database/migrations/subcategory_description.php #update single file

Database Table Relationship

 
# $table->unsignedBigInteger('user_id');
# $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

Post and Comments Model Relationship

 
# Post Model Relationship Code
class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

# Comment Model Relationship Code class Comment extends Model { public function post() { return $this->belongsTo(Post::class); } }
# Display All Comments public function show($postId) { $post = Post::with('comments')->find($postId); return view('posts.show', compact('post')); }

Database existing table update without losing any old data.

 
# Database Table Code
 public function up()
    {
        Schema::table('your_table_name', function (Blueprint $table) {
            $table->string('new_column1');
            $table->integer('new_column2');
        });
    }

    public function down()
    {
        Schema::table('your_table_name', function (Blueprint $table) {
            $table->dropColumn('new_column1');
            $table->dropColumn('new_column2');
        });
    }

Optimize, Clear Cache and Config

 
$ php artisan optimize:clear
$ php artisan cache:clear
$ php artisan config:clear

Image ADD

Image Add Code Controller

 
## Department image 1 
     $image1 = $request->file('profile_pic');
     if ($request->hasfile('profile_pic')) {
         $extension = $image1->getClientOriginalExtension();
         $department_image_name = $user->name . '-photo-.' . $extension;
         $image1->move('assets/users/', $department_image_name);
         $user->profile_pic = $department_image_name;
      }

Image Delete Code Controller

 
## Image Delete Code 
public function destroy($id){
  
    $item = reg_user::find($id);
   
    if (!$item) {
        return redirect()->route('users_home')->with('error', 'Item not found!');
    }

    $destination = public_path('/assets/users/') . $item->profile_pic;
    if (File::exists($destination)) {
        File::delete($destination);
    }
    $item->delete();
    return redirect()->route('users_home')->with('success', 'Item deleted successfully!');

}   

Laravel 11 + VUE 3

Create New Laravel Project

 
$ composer create-project --prefer-dist laravel/laravel crudapplication

How To Install Vue 3 on Laravel 11

 
$ npm install vue@latest
$ npm install @vitejs/plugin-vue
  
## if Error ## 
 npm i @vitejs/plugin-vue@4.0.0
  
  
## vite.config.js ## 
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/sass/app.scss',
                'resources/js/app.js',
                'resources/css/app.css',
            ],
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
      
    ],
    resolve: {
        alias: {
            vue: 'vue/dist/vue.esm-bundler.js',
        },
    },
});

  
  
  
## index.blade.php ##

<html lang='en' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
head>
    <meta charset='UTF-8'/>
    <meta content='width=device-width, initial-scale=1.0' name='viewport'/>
    <title>Document</title>
/head>
<body>
    @vite('resources/css/app.css')
    <div id='app'>
        
    </div>
    @vite('resources/js/app.js')
</body>
</html>

  
  

  
  
## app.js ## 
import { createApp } from 'vue';
import App from './App.vue'
import router from'./routes.js'

const app = createApp({});



createApp(App).use(router).mount("#app")


## App.vue ## 

<template>
    <router-view></router-view>
  </template>
  <script>
  export default {
 
  }
  </script>
  
  
 
  

$ npm i vue-router@next
or
$ npm install vue-router@4

## routes.js ##
import { createWebHistory, createRouter } from 'vue-router'
import test from './test.vue'


const routes = [

    {
        name: 'test',
        path: '/',
        component: test,

    },

];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

export default router;

  

Enable or Disable Laravel Debugbar

Through .env file

 
$ DEBUGBAR_ENABLED = FALSE 
$ DEBUGBAR_ENABLED = TRUE

Run for changes in .env file

 
$ php artisan cache:clear
$ php artisan config:cache

Through app/Providers/AppServiceProvider.php

 
class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        \Debugbar::disable();
    }
}

Use Regular Expression To Replace All Code in Once:

# I want to remove data-reactid="anythingcanbe"  from while document is VSCode
$ \sdata-reactid="[^"]*"

Laravel Tutorials

Linux Bash


Open bashrc

 
$ sudo nano ~/.bashrc

Change alias

 
$ alias python=var/location/python3.exe

Reload bashrc

 
$ source ~/.bashrc

Linux Basic Command


Create Folder

 
$ mkdir foldername

Delete Folder

 
$ rmdir foldername

Create File

 
$ touch filename.extension

Delete File

 
$ rm filename.extension

Read File In Terminal

 
$ cat filename

Edit File in Text Editor

 
$ nano filename

Symlink

 
root@linux:~/target_folder_in$ sudo ln -s /home/target_folder_out/Filename_YAMiN.yml

Modify your hosts file /etc/hosts

 
$ Go folder -> /etc/  and open  hosts file and add  127.0.0.1   needyamin.com 

Enable Virtual Host

 
$ sudo ln -s /etc/apache2/sites-available/needyamin.com.conf /etc/apache2/sites-enabled/

Restart Apache:

 
$ sudo systemctl restart apache2

Git Command Line


At first clone git repository

 
$ git clone http://github.com/needyamin/target-repository.git

Create an empty Git repository or reinitialize an existing one

 
$ git init 

Add Your Edited Files to Git

 
$ git add .

Check Added Git Status

 
$ git status

Commit your added Git files

 
$ git commit -m "First commit"

Push Your Files to the Main Origin Git Repository

 
$ git push origin main

If want to make new Branch

 
$ git checkout -b yourbranchname

Docker Command


Docker Container and Access

  
# Check Container Information
$ docker ps
  
# Access This container
$ docker exec -it php-container bash
  
# IF exec not working
$ docker exec -it f479be191869 sh

# Direct Exec CLI command inside Container
$ docker exec -it eb0b4128cd88 php artisan migrate

# Direct Run PHP Command Inside Docker
$ docker compose run --rm artisan migrate:fresh 

Rebuild Docker Container

$ docker compose down
$ docker compose build
$ docker compose up
  
# Rebuild the Dockerfile single image:
$ docker compose build php

Delete Everything

$ sudo docker builder prune
$ sudo docker system prune -a --volumes
$ sudo docker system prune -a

# Stop All Running Containers
$ docker stop $(docker ps -q)

# Remove All Containers
$ docker rm $(docker ps -a -q)

# Combined Command to Stop and Remove All Containers
$ docker stop $(docker ps -q) AND docker rm $(docker ps -a -q)

  
  

Manage Docker with Local User


  $ sudo usermod -aG docker $USER
  $ newgrp docker
# Check Docker Status
sudo systemctl status docker
# Test Docker Installation
$ docker run hello-world

Docker Compose

# The following only builds the images, does not start the containers:
$ docker compose build
# The following builds the images if the images do not exist and starts the containers:
$ docker compose up
# If you add the --build option, it is forced to build the images even when not needed:
$ docker compose up --build
# The following skips the image build process:
$ docker compose up --no-build

Docker Run a container

# Build a docker imag
$ docker build . -t webapp
# Run a container with
$ docker run --rm -it -p 8080:80 webapp

Database Connect


MySQLi Object-Oriented



$servername = "localhost";
$username = "username";
$password = "password";

// Connection Name
$conn = new mysqli($servername, $username, $password);

// Check Connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";



PHP Data Objects (PDO)


$servername = "localhost";
$username = "username";
$password = "password";

try {
  $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
  
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} 

  catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}


Create Statement


MYSQLi Create Statement


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; 

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "
" . $conn->error; } $conn->close();

PDO Create Statement


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  
  $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
  
  // use exec() because no results are returned
  $conn->exec($sql);
  
  echo "New record created successfully";
} 

  catch(PDOException $e) {
  echo $sql . "" . $e->getMessage();
}

$conn = null;


Delete Statement


MYSQLi DELETE Statement


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {
  echo "Record deleted successfully";
} else {
  echo "Error deleting record: " . $conn->error;
}

$conn->close();	


PDO DELETE Statement


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  // sql to delete a record
  $sql = "DELETE FROM MyGuests WHERE id=3";

  // use exec() because no results are returned
  $conn->exec($sql);
  echo "Record deleted successfully";
} 

  catch(PDOException $e) {
  echo $sql . "" . $e->getMessage();
}

$conn = null;


Select Data Statement


MYSQLi Select Statement


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 results"; } $conn->close();

PDO Select Statement


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
	
  // output data of each row
  while($row = mysqli_fetch_assoc($result)) {
    echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "";
  }
} 

  else {
  echo "0 results";
}

mysqli_close($conn);


Update Data Statement


MYSQLi Update Statement


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {
  echo "Record updated successfully";
} else {
  echo "Error updating record: " . $conn->error;
}

$conn->close();


PDO Update Statement


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

  // Prepare statement
  $stmt = $conn->prepare($sql);

  // execute the query
  $stmt->execute();

  // echo a message to say the UPDATE succeeded
  echo $stmt->rowCount() . " records UPDATED successfully";
} 

  catch(PDOException $e) {
  echo $sql . "
" . $e->getMessage(); } $conn = null;

Basic CRUD with POST Form Action


Basic Insert POST Method

  
    # Connect to mysql server 
    $connection = new mysqli ('localhost','username','password','database_name');

    # If Condition Check Error
    if ($connection->connect_error) {
        die("database not found"); #data stop;
    } 
    
    # If Condition Check True
    else {
    #print"success";
    }
    
   ############ When Clicked Action POST Start ############
    if(isset($_POST['submit_hit']))  {
    
  # Store post value data in Variables 
    $f = $_POST['fname']; 
    $l = $_POST['lname'];
    $e = $_POST['email'];
    $p = $_POST['password'];
    $p = md5($p);
    
    # Fire SQL Query
    $sql = "INSERT INTO `sign_up` (`id`, `fname`, `lname`, `email`, `password`) VALUES (NULL, '$f', '$l', '$e', '$p')";
    $connection->query($sql);
    echo "your sign up process is successfully done";
    
    }

 ############ When Clicked Action POST End ############

  
  

Basic SELECT

  
   # Connect To The Database Server 
    $connection = new mysqli ('localhost','needyamin','Yamin143','project2'); 
  
     # SELECT ALL FROM Database Table
    $f = "SELECT * FROM `sign_up`";
    $result = $connection->query($f);
    
     # While Loop Fetch All Table Rows
    while ($row = $result->fetch_assoc()){
      
   # Echo your Rows     
    echo $row['id'];
    echo $row['fname'];
    echo $row['lname'];
    echo $row['email'];
    echo $row['password'];  
    };

  
  

Database Table Query


Create a MySQL Table (DEMO DATABASE TABLE)



CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)



SQL CRUD Operations


SQL Create/INSERT


INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')	


SQL Read/SELECT


SELECT * FROM MyGuests

or

SELECT id, firstname, lastname FROM MyGuests	


SQL Write/UPDATE


UPDATE MyGuests SET lastname='Doe' WHERE id=1	


SQL Delete


DELETE FROM MyGuests WHERE id=3	


Join Statement


Inner Join
SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;

LEFT JOIN
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;

RIGHT JOIN
SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;

Full JOIN
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name WHERE condition; 



AND, OR and NOT Operators


AND 
SELECT  column1, column2, FROM table_name WHERE  condition1 AND  condition2 AND  condition3; 

OR 
SELECT  column1, column2, FROM table_name WHERE  condition1 OR  condition2 OR  condition3; 

NOT
SELECT column1, column2, FROM table_name WHERE NOT condition; 




SQL LIKE %value%


SELECT column1, column2, FROM table_name WHERE columnN LIKE % pattern values %; 


SQL DESC/ASC


DESC
SELECT column1, column2, FROM table_name ORDER BY column1, column2, DESC; 

ASC
SELECT column1, column2, FROM table_name ORDER BY column1, column2, ASC; 



SQL ADVANCED


SQL BACKUP DATABASE  
BACKUP DATABASE testDB TO DISK = 'D:\backups\testDB.bak'; 

SQL DROP DATABASE  
DROP DATABASE databasename;




Django Statement


Update Statement


Install Django

 
  $ pip3 install django
  
  $ django-admin startproject name
  
  $ python manage.py runserver


Install APP

 
  $ python manage.py startapp name


Django Statement 2


Update Statement


Install Django

 $ pip3 install django


Django Statement 3


Update Statement


update Django

 update


THEME AND DESIGN

THEME AND DESIGN

 
  $  http://jonayed.com/file/ 


How to install virtualenv


Install pip first

$ sudo apt-get install python3-pip

Then install virtualenv using pip3

$ sudo pip3 install virtualenv 

Now create a virtual environment

$ virtualenv venv 

you can use any name insted of venv


You can also use a Python interpreter of your choice

$ virtualenv -p /usr/bin/python2.7 venv

Active your virtual environment:

$ source venv/bin/activate
(Windows) $ venv\Scripts\activate

Using fish shell:

$ source venv/bin/activate.fish

To deactivate:

$ deactivate

Create virtualenv using Python3

$ virtualenv -p python3 myenv

Instead of using virtualenv you can use this command in Python3

$ python3 -m venv myenv

Install requirments:

$ pip install -r requirments.txt



What is CRUD?

In computer programming, create, read, update, and delete are the four basic operations of persistent storage. CRUD is also sometimes used to describe user interface conventions that facilitate viewing, searching, and changing information using computer-based forms and reports.
Source Code: GitHub
Copyright © 2021-- by YAMiN | Powered by Blogger