sábado, 15 de febrero de 2025

SANITIZE_NUMBER

<?php 

 $nums="12a";

echo filter_var($nums,FILTER_SANITIZE_NUMBER_INT); //12


//https://www.php.net/manual/en/filter.constants.php#constant.filter-sanitize-string

//https://www.php.net/manual/en/function.filter-var.php


?>

Date forma option

 https://www.php.net/manual/en/datetime.format.php

viernes, 14 de febrero de 2025

save csv on db

 <?php

// Database connection

$mysqli = new mysqli("localhost", "username", "password", "database_name");


// Check for connection error

if ($mysqli->connect_error) {

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

}


// Open the CSV file

if (($handle = fopen("data.csv", "r")) !== FALSE) {

    // Skip the first line if it contains the header

    fgetcsv($handle);


    // Prepare the SQL query for inserting data

    $stmt = $mysqli->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");

    $stmt->bind_param("ssi", $name, $email, $age); // 'ssi' means string, string, integer


    // Read each line of the CSV and insert the data into the database

    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {

        $name = $data[0];    // First column: name

        $email = $data[1];   // Second column: email

        $age = (int)$data[2]; // Third column: age (cast to integer)


        // Execute the prepared statement

        if (!$stmt->execute()) {

            echo "Error inserting record: " . $stmt->error . "<br>";

        }

    }


    // Close the prepared statement and file handle

    $stmt->close();

    fclose($handle);

} else {

    echo "Error opening the file.";

}


// Close the database connection

$mysqli->close();

?>


convert seconds to minutes

 function MinSecs($time){

    $Seconds = $time % 60;  // Seconds is the remainder when divided by 60

    $Minutes = floor($time / 60);  // Minutes is the total time divided by 60, rounded down

    $arr = [$Minutes, $Seconds];  // Return minutes first, then seconds


    return $arr;

}


print_r(MinSecs(841));

prepare sttament

 <?php


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");


// Check for connection errors

if ($mysqli->connect_error) {

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

}

/* Prepare an insert statement */

$stmt = $mysqli->prepare("INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)");


// Check if the statement was prepared successfully

if (!$stmt) {

    die("Error preparing the statement: " . $mysqli->error);

}


/* Bind variables to parameters */

$stmt->bind_param("sss", $val1, $val2, $val3);


$val1 = 'Stuttgart';

$val2 = 'DEU';

$val3 = 'Baden-Wuerttemberg';


/* Execute the statement */

if ($stmt->execute()) {

    printf("New record has ID %d.\n", $mysqli->insert_id);

} else {

    echo "Error inserting record: " . $stmt->error;

}


// Close the connection

$mysqli->close();

?>

miércoles, 12 de febrero de 2025

martes, 11 de febrero de 2025

insert

<?php


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);


// Create a connection to the database

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");


// Check for connection errors

if ($mysqli->connect_error) {

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

}


// Check if table exists before creating it

if ($mysqli->query("SHOW TABLES LIKE 'myCity'")->num_rows == 0) {

    // If the table doesn't exist, create it by duplicating the structure of the 'City' table

    if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {

        die("Error creating table: " . $mysqli->error);

    }

} else {

    echo "Table 'myCity' already exists.\n";

}


// Insert a new record into 'myCity'

$query = "INSERT INTO myCity (ID, Name, CountryCode, District, Population) VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";

if ($mysqli->query($query)) {

    printf("New record has ID %d.\n", $mysqli->insert_id);

} else {

    echo "Error inserting record: " . $mysqli->error;

}


// Close the connection

$mysqli->close();

?>


Simple SQL Query

<?php


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);


$mysqli = new mysqli("localhost", "root", "", "asterisk");


// Check for connection errors

if ($mysqli->connect_error) {

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

}


$query = "SELECT now() as now";


// Execute the query and check for errors

$result = $mysqli->query($query);


// Check if the query was successful

if (!$result) {

    die("Query failed: " . $mysqli->error);

}


/* Get the number of fields in the result set */

$field_cnt = $result->field_count;


/* Get the number of rows in the result set */

$row_cnt = $result->num_rows;


/* Fetch associative array */

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

    echo "Total of values: Fields = $field_cnt, Rows = $row_cnt, Current Time = $row['now']<br>";

}


$mysqli->close();

?>


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

<?php


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);


$mysqli = new mysqli("localhost", "my_user", "my_password", "world");


// Check for connection errors

if ($mysqli->connect_error) {

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

}


$result = $mysqli->query("SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");


// Check if query was successful

if (!$result) {

    die("Query failed: " . $mysqli->error);

}


// Fetch all rows as an associative array

$rows = $result->fetch_all(MYSQLI_ASSOC);


foreach ($rows as $row) {

    printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);

}


$mysqli->close();

?>


multiquery

<?php


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);


// Create a connection to the database

$mysqli = new mysqli("localhost", "root", "", "asterisk");


// Check connection

if ($mysqli->connect_error) {

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

}


// Multiple SELECT queries to execute

$query = "SELECT CURDATE() AS DATE;

          SELECT NOW() AS NOW;

          SELECT YEAR(NOW()) AS YEAR";


// Execute multiple queries

if ($mysqli->multi_query($query)) {

    do {

        // Store the result set of each query

        if ($result = $mysqli->store_result()) {

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

                // Correct way to access values from the associative array

                // Here we check if the keys exist and print the results accordingly

                if (isset($row['DATE'])) {

                    echo "DATE: " . $row['DATE'] . " | ";

                }

                if (isset($row['NOW'])) {

                    echo "NOW: " . $row['NOW'] . " | ";

                }

                if (isset($row['YEAR'])) {

                    echo "YEAR: " . $row['YEAR'];

                }

                echo "<br>";

            }

            $result->free(); // Free result set

        }


        // Print divider if there are more results

        if ($mysqli->more_results()) {

            echo "-----------------\n";

        }

    } while ($mysqli->next_result());

}


$mysqli->close(); // Close the database connection


?>


viernes, 7 de febrero de 2025

getting the key name for a value

<? $array = [ 'a' => 'dog', 'b' => 'cat', 'c' => 'cow', 'd' => 'duck', 'e' => 'goose', 'f' => 'elephant' ]; print_r(array_find_key($array,function($v){ return ($v=="goose");})); ?>

jueves, 6 de febrero de 2025

Seraching key and retuning value

<?php

 $search_array = array('first' => 1334, 'second' => 4);

echo (array_key_exists('first', $search_array)==true?$search_array['first']:0);  //1334


?>

array_filter( ) simplified

 $elements=[13,45,101,33,1,0];


$arr= array_filter($elements,function($value){ return($value>100);  });


print_r($arr);   //101

lunes, 3 de febrero de 2025

searching in string as array

 $text="Gobierno afirma que el país tiene la segunda canasta alimentaria más baja de la región";


echo in_array(strtolower('GoBierno'),$arr1=explode(' ',strtolower($text)));  //1


print_r($arr1);



sábado, 1 de febrero de 2025

custom array filter values

$arr=[12,31,14,101,9,220];



function test(array $arr,int $val){

  if(gettype($arr)!="array" || gettype($val)!="integer"){ return 0; exit();}

  $holder=array();

foreach($arr as $key=>$value){

  

 if($value>$val){ $holder[]=$value;}

}

 return $holder;                 

}

$holder=test($arr,20);

print_r($holder);

echo "<br>";


echo count($arr)==count($holder)?"all_values_match":(count($holder)>0?"any_match":-1);