viernes, 27 de diciembre de 2024

select

 #!/usr/bin/php -q


<?php


// Include external configuration and helper files

require("/root/fm/db_con.php");     // Database connection details


// Establish a connection using MySQLi (object-oriented style)

$conn = new mysqli($host, $user, $password, $database);


// Check if the connection was successful

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}


// Define the query to fetch leads

$query = "SELECT lead_id, phone FROM leads";


// Execute the query and check for errors

if ($result = $conn->query($query)) {

    

    // Check if there are any rows returned

    if ($result->num_rows > 0) {

        // Loop through the result set and output each row

        while ($row = $result->fetch_assoc()) {

            // Safely output the values (HTML escaped for safety)

            echo htmlspecialchars($row['lead_id']) . ", " . htmlspecialchars($row['phone']) . "\n";

        }

    } else {

        // If no rows were found

        echo "No records found.\n";

    }


    // Free result set to free up memory

    $result->free();

} else {

    // If query fails, output an error message

    echo "Error executing query: " . $conn->error . "\n";

}


// Close the database connection

$conn->close();


?>


miércoles, 25 de diciembre de 2024

php tenary operator logical opertor

 echo $cmd=(45>13 && 211<100 ?"AMBIORIX":"RODRIGUEZ");

 as only  1  of the condition is true will return RODRIGUEZ



 echo $cmd=(45>13 || 211<100 ?"AMBIORIX":"RODRIGUEZ");

in tis case will return AMBIORIX as at least 1  is true

----------------------------------------


$argv=[1,3];


 echo $var=(count($argv)!=2)?exit():1;

miércoles, 18 de diciembre de 2024

accesing to a multidimensional array value

,<?php


   $array = array(

    "foo" => "bar",

    42    => 24,

    "multi" => 

  array(

         "dimensional" => array(

             "array" => "foo"

         )

     ));



echo $array['multi']['dimensional']['array'];  //foo


?>

Other example



$i=1; 

  $pos=array();

 


  

   $pos[$i]=["familyId"=>"12","familylocalName"=>"Ambiorix"];



  //$pos[1] is an array so you can  access direct to is key value $pos[1]['familyId']; 



echo  $pos[1]['familyId'];

///

jueves, 5 de diciembre de 2024

applying a call back function to all keys on an array.

 $array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);


$array2 = array('green' => 3, 'blue1' => 1, 'yellow' => 7, 'cyan'   => 8);



function test($n,$search_array){

return  array_key_exists($n, $search_array); 

}



echo "<br>";

print_r(array_map('strtoupper',array_keys($array1)));  

// will print Array ( [0] => BLUE [1] => RED [2] => GREEN [3] => PURPLE )


echo "<br>";


echo test('yellow',$array2);   //  echo 1




miércoles, 27 de noviembre de 2024

check if a value is not or is in an array and create other array with those values

 <?php



$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);

$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 2, 'cyan'   => 1);



$arr=array();



foreach($array1 as $value){

if (!in_array($value, $array2)) {

$arr[]=$value;

}


}


print_r($arr);



?>


Array ( [0] => 3 [1] => 4 )

sábado, 2 de noviembre de 2024

AWS s3 upload

Step 1: Install Required Packages

 sudo apt update

sudo apt install php php-cli php-zip unzip

sudo apt install php-xml

Step 2: Download and Install Composer

curl -sS https://getcomposer.org/installer | php

Move Composer to a Global Location:
sudo mv composer.phar /usr/local/bin/composer

Make It Executable:

sudo chmod +x /usr/local/bin/composer

Step 3: Verify the Installation

composer --version

Step 4: Create a PHP Project and Install Dependencies

cd /path/to/your/project

composer init

composer require aws/aws-sdk-php 

#############


<?php
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// Create a new S3 client
$s3Client = new S3Client([
    'region' => 'us-east-1', // e.g. us-west-2
    'version' => 'latest',
    'credentials' => [
        'key'    => 'AKMNB#888888PA',
        'secret' => 'I54444444444444a'
    ],
]);


$bucket = 'asteriskrecordings';
$filePath = "$argv[1]"; // Local file path
$keyName = basename($filePath); // Use the base name of the file

try {
    // Upload the file
    $result = $s3Client->putObject([
        'Bucket' => $bucket,
        'Key'    => $keyName,
        'SourceFile' => $filePath
    ]);

    echo "File uploaded successfully. File URL: " . $result['ObjectURL'] . "\n";
} catch (AwsException $e) {
    // Output error message if upload fails
    echo "Error uploading file: " . $e->getMessage() . "\n";
}
?>




...........

function version

<?php
require '/root/fm/aws/vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// Create a new S3 client with hardcoded credentials
$s3Client = new S3Client([
    'region' => 'us-east-1', // AWS region (e.g., us-west-2, us-east-1)
    'version' => 'latest', // Use the latest version of the API
    'credentials' => [
        'key'    => 'AKI11A', // Hardcoded AWS Access Key
        'secret' => 'I5HTgA33brbpj/Sz' // Hardcoded AWS Secret Key
    ],
]);

function s3_name_upload($filePath)
{
    $bucket = 'asteriskrecordings';  // Your S3 bucket name

    // Validate that the file exists
    if (!file_exists($filePath)) {
        echo "Error: The file '$filePath' does not exist.\n";
        return;
    }

    $keyName = basename($filePath); // Use the base name of the file for the S3 key

    try {
        // Upload the file to S3
        $result = $GLOBALS['s3Client']->putObject([
            'Bucket' => $bucket,
            'Key'    => $keyName,
            'SourceFile' => $filePath
        ]);

        echo "File uploaded successfully. File URL: " . $result['ObjectURL'] . "\n";
    } catch (AwsException $e) {
        // Output error message if upload fails
        echo "Error uploading file: " . $e->getMessage() . "\n";
    }
}

// Ensure a file path argument is passed when running the script
if ($argc < 2) {
    echo "Usage: php script.php <file-path>\n";
    exit(1);
}

$filePath = $argv[1];  // Local file path passed as a command-line argument
s3_name_upload($filePath);
?>

sábado, 19 de octubre de 2024

calculate_time_difference

 <?php


function calculate_time_difference($datetime_str) {

    // Split the input string into date and time components

    $datetime_parts = explode(' ', $datetime_str);

    

    // Extract the date and time

    $date_parts = explode('-', $datetime_parts[0]);

    $time_parts = explode(':', $datetime_parts[1]);

    

    // Normalize the date and time into integers for mktime

    $year = (int)$date_parts[0];

    $month = (int)$date_parts[1];

    $day = (int)$date_parts[2];

    

    $hour = (int)$time_parts[0];

    $minute = (int)$time_parts[1];

    $second = (int)$time_parts[2];

    

    // Create the target time using mktime

    $target_time = mktime($hour, $minute, $second, $month, $day, $year);

    

    // Get the current time

    $current_time = time();

    

    // Calculate the difference in seconds

    $diff = $current_time - $target_time;

    

    // Convert seconds into minutes and seconds

    $minutes = floor($diff / 60);    

    $seconds = $diff % 60;

    

    // Output the difference in "minutes:seconds" format

    echo "$minutes:$seconds\n";

    

    // Output the current date and time

    echo date("Y-m-d H:i:s");

}


// Example usage: Pass a date string in the "Y-m-d H:i:s" format

$datetime_str = "2024-10-20 01:45:16";

calculate_time_difference($datetime_str);


?>


viernes, 18 de octubre de 2024

convert to sec and mis

 <?php

function convert_to_mins($s){

    

$minutes= floor($s/60);    

$seconds=$s % 60;


echo "$minutes:$seconds";


    

    

}


function convert_to_secs($min){


$seconds= $min * 60;


echo "$seconds";

    

    

}



convert_to_mins(180);

echo "\n";

convert_to_secs(3);



sábado, 12 de octubre de 2024

filter array if value is >=70

 <?php

function pass($var){

    

  return $var>=70;

    

}


$notas=array("Jose"=>90,"Ambiorix"=>100,"Maria"=>65,90);

print_r(array_filter($notas,"pass"));


?>


Array

(

    [Jose] => 90

    [Ambiorix] => 100

    [0] => 90

)


domingo, 6 de octubre de 2024

MYSQL TRIGGERS EXAMPLE

 DELIMITER //


CREATE TRIGGER ProductSellPriceUpdateCheck 

    AFTER UPDATE  

    ON Products FOR EACH ROW  

BEGIN

IF NEW.SellPrice <= NEW.BuyPrice THEN

INSERT INTO Notifications(Notification,DateTime) 

VALUES(CONCAT(NEW.ProductID,' was updated with a SellPrice of ', NEW.SellPrice,' which is the same or less than the BuyPrice'), NOW()); 

    END IF;

END //




DELIMITER //


CREATE TRIGGER ProductSellPriceInsertCheck 

    AFTER INSERT  

    ON Products FOR EACH ROW  

BEGIN

IF NEW.SellPrice <= NEW.BuyPrice THEN

INSERT INTO Notifications(Notification,DateTime) 

VALUES(CONCAT('A SellPrice same or less than the BuyPrice was inserted for ProductID ', NEW.ProductID), NOW()); 

    END IF;

END //



DELIMITER //


CREATE TRIGGER NotifyProductDelete 

    AFTER DELETE   

    ON Products FOR EACH ROW   

INSERT INTO Notifications(Notification, DateTime) 

    VALUES(CONCAT('The product with a ProductID ', OLD.ProductID,' was deleted'), NOW()); 

END //

DELIMITER ;

sábado, 5 de octubre de 2024

MySQl official Guide

 https://dev.mysql.com/doc/refman/8.4/en/

https://developers.facebook.com/docs/pages-api/comments-mentions/

Get comments

To get the comments for a Page post, send a GET request to the /page_post_id/comments endpoint with the fields parameter set to a comma-separated list that includes the message field, to get the content for the comment and the from field, to get the Page-scoped ID (PSID) for the person or Page who commented on the post, if you would like to @mention the person or Page in the comment.

Example Request

Formatted for readability. Replace bold, italics values, such as page_post_id, with your values.
curl -i -X GET "https://graph.facebook.com/page_post_id/comments?fields=from,message"

On success, your app receives the following JSON response with the commentor's name, PSID, message and the comment ID:

{
  "data": [
    {
      "created_time": "2020-02-19T23:05:53+0000",
      "from": {
        "name": "commentor_name",
        "id": "commentor_PSID"
      },
      "message": "comment_content",
     "id": "comment_id"
    }
  ],
  "paging": {
    "cursors": {
      "before": "MQZDZD",
      "after": "MQZDZD"
    }
  } 

}  

https://developers.facebook.com/docs/pages-api/comments-mentions/