#php if array is empty
Explore tagged Tumblr posts
Text
Easy ways to check whether your PHP Array is empty or not by using simple syntaxes.
#php empty array#check if array is empty php#php if array is empty#php array empty#php check if array is empty
0 notes
Text
Vogon Ajax Loop Interface
I wasn't being followed by as many people who might care at the time I wrote this in 2020, so here's a quick refresher on how the Ajax Loop Interface works.
An ajax controller is built that includes the backend ALI class. This class accepts an array, an initialization model that generates and array to be stored in $_SESSION (useful for file scans) or an SQL statement that can be run to generate an array.
As another property, it accepts an additional model that is designed to do whatever action is needed on a single member of this array.
This controller will then switch modes based on the current state of the process defined by the GET parameters set in the ajax request. If nothing is provided, it's an initialization state, if provided with a count and offset, we need to run the model for the given member of the array.
If the count and offset are provided but the array is currently missing (such as when resuming a process that errored out or timed out), the controller can re-run the initialization step to rebuild the array, and then instruct the frontend client to make the request again.
The frontend view then, is a javascript object that manages the requests and displays the messages provided by the various models, as well as a convenient progress bar.
For context of how quick this makes it to set up these jobs, here's the full text of the audio import controller
<?php
if(empty($_GET['dir'])){ $_GET['dir'] = ''; }
load_class('ajax_loop_interface');
$ali = new ajax_loop_interface([ 'mode' => 'session_array', 'init_model' => 'audio_import_init', 'init_data' => [ 'dir' => $_GET['dir'] ], 'model' => 'audio_import', 'ext' => 'audio', 'var_name' => 'f' ]);
2 notes
·
View notes
Text
How to check Email and username availability live using jquery/ajax, PHP and PDO
In this tutorial, We will learn how to How to check Email and username availability live using jQuery/ajax and PHP-PDO.
Click : https://phpgurukul.com/how-to-check-email-and-username-availability-live-using-jquery-ajax-php-and-pdo/
File Structure for this tutorials
index.php (Main File)
config.php (Database Connection file)
check_availability.php (Used to check the Email and User availability)
Create a database with name demos. In demos database, create a table with name email_availabilty Sample structure of table email_availabilty
CREATE TABLE IF NOT EXISTS `email_availabilty` (
`id` int(11) NOT NULL,
`email` varchar(255) NOT NULL,
`username` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
2. Create a database connection file
config.php
<?php
//DB Connection
define(‘DB_HOST’,’localhost’);
define(‘DB_USER’,’root’);
define(‘DB_PASS’,’’);
define(‘DB_NAME’,’demos’);
// Establish database connection.
try
{
$dbh = new PDO(“mysql:host=”.DB_HOST.”;dbname=”.DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => “SET NAMES ‘utf8’”));
}
catch (PDOException $e)
{
exit(“Error: “ . $e->getMessage());
}
3. Now Create an HTML form index.php
<?php
include_once(“config.php”);
?>
<table>
<tr>
<th width=”24%” height=”46" scope=”row”>Email Id :</th>
<td width=”71%” ><input type=”email” name=”email” id=”emailid” onBlur=”checkemailAvailability()” value=”” class=”form-control” required /></td>
</tr>
<tr>
<th width=”24%” scope=”row”></th>
<td > <span id=”email-availability-status”></span> </td>
</tr>
<tr>
<th height=”42" scope=”row”>User Name</th>
<td><input type=”text” name=”username” id=”username” value=”” onBlur=”checkusernameAvailability()” class=”form-control” required /></td>
</tr>
<tr>
<th width=”24%” scope=”row”></th>
<td > <span id=”username-availability-status”></span> </td>
</tr>
</table>
4. Jquery/ajax script where you pass variable to check_availability.php page. put this in index.php inside head.
<script>
function checkemailAvailability() {
$(“#loaderIcon”).show();
jQuery.ajax({
url: “check_availability.php”,
data:’emailid=’+$(“#emailid”).val(),
type: “POST”,
success:function(data){
$(“#email-availability-status”).html(data);
$(“#loaderIcon”).hide();
},
error:function (){}
});
}
function checkusernameAvailability() {
$(“#loaderIcon”).show();
jQuery.ajax({
url: “check_availability.php”,
data:’username=’+$(“#username”).val(),
type: “POST”,
success:function(data){
$(“#username-availability-status”).html(data);
$(“#loaderIcon”).hide();
},
error:function (){}
});
}
</script>
5.check_availability.php page in this page you will check the availability of email or email.
<?php
require_once(“config.php”);
//code check email
if(!empty($_POST[“emailid”])) {
$uemail=$_POST[“emailid”];
$sql =”SELECT email FROM email_availabilty WHERE email=:email”;
$query= $dbh -> prepare($sql);
$query-> bindParam(‘:email’, $uemail, PDO::PARAM_STR);
$query-> execute();
$results = $query -> fetchAll(PDO::FETCH_OBJ);
if($query -> rowCount() > 0)
echo “<span style=’color:red’> Email Already Exit .</span>”;
else
echo “<span style=’color:green’> Email Available.</span>”;
}
// End code check email
//Code check user name
if(!empty($_POST[“username”])) {
$username=$_POST[“username”];
$sql =”SELECT username FROM email_availabilty WHERE username=:username”;
$query= $dbh -> prepare($sql);
$query-> bindParam(‘:username’, $username, PDO::PARAM_STR);
$query-> execute();
$results = $query -> fetchAll(PDO::FETCH_OBJ);
if($query -> rowCount() > 0)
echo “<span style=’color:red’> Username already exit .</span>”;
else
echo “<span style=’color:green’> Username Available.</span>”;
}
// End code check username
?>
PHP Gurukul
Welcome to PHPGurukul. We are a web development team striving our best to provide you with an unusual experience with PHP. Some technologies never fade, and PHP is one of them. From the time it has been introduced, the demand for PHP Projects and PHP developers is growing since 1994. We are here to make your PHP journey more exciting and useful.
Website : https://phpgurukul.com
0 notes
Text
Reading a CSV File using PHP
When working with CSV (Comma-Separated Values) files in PHP, you may need to read and process data from them. Here's a step-by-step guide on how to read a CSV file using PHP.
First step: Link the filepath of your CSV file. It can be from the Internet like Github Raw Usercontent
$filename = 'https://raw.githubusercontent.com/jclosure/us-500-graph/master/data/us-500.csv';
Second step: Define the mode
$mode = 'r';
Read Mode ('r'): reading only Write Mode ('w'): Opens the file for writing. If the file already exists, it will be truncated (emptied). If the file doesn't exist, a new file will be created. Append Mode ('a'): Opens the file for writing, but it appends new data to the end of the file Read and Write Mode ('r+'): Opens the file for both reading and writing. Write and Read Mode ('w+'): Opens the file for both writing and reading. If the file already exists, it will be truncated; if not, a new file will be created. Append and Read Mode ('a+'): Opens the file for both appending and reading. It will place the pointer at the end of the file.
Third step: Open the file using fopen(). It returns a file pointer that can be used for reading. Store it in a variable for easier access later.
$file = fopen($filename, $mode);
To read a row from the CSV file:
The fgetcsv() reads and parses a line from the file and returns it as an array of values. We can store this array in a variable like $row, which will now contain the values of the row. We can now access the row values like a normal array, example, $row[0] and store it inside an HTML tag like <td>.
To read all rows from the CSV file:
Fgetscv() returns an array of values from a specific row. A $row variable stores this array. We can just do a loop that checks if $row is empty or false. If it's empty, it means fgetscv wasn't able to read a row anymore from the file.
Remember to fclose();
Remember to do an if-else that checks if the file was successfully opened or not.
0 notes
Text
Filling a PHP array dynamically means that instead of hardcoding the values, you're adding values to the array based on some logic, external input, or data sources. Here's a basic overview and some examples:
1. Create an Empty Array
You can create an empty array using the 'array()' function or the '[]' shorthand.
$dynamicArray = array(); // OR $dynamicArray = [];
2. Add Elements to the Array
You can add elements to an array in various ways:
Append to the array:
$dynamicArray[] = 'value1'; $dynamicArray[] = 'value2';
Add with a specific key:
$dynamicArray['key1'] = 'value1'; $dynamicArray['key2'] = 'value2';
3. Dynamically Filling the Array
Here's how you can fill an array based on various scenarios:
From a database (using PDO for this example)
$stmt = $pdo->query("SELECT value FROM some_table"); while ($row = $stmt->fetch()) { $dynamicArray[] = $row['value']; }
From a form (using POST method as an example):
if (isset($_POST['inputName'])) { $dynamicArray[] = $_POST['inputName']; }
Based on some logic:
for ($i = 0; $i < 10; $i++) { if ($i % 2 == 0) { $dynamicArray[] = $i; } }
This would fill $dynamicArray with even numbers between 0 and 9.
4. Tips and Best Practices
Sanitize external input: Always sanitize and validate data, especially when it's coming from external sources like user input, to ensure security.
Use associative arrays wisely: If you're using string keys, ensure they're unique to avoid overwriting values.
Check existing values: When adding to an array, you may want to check if a value already exists to avoid duplicates.
if (!in_array($value, $dynamicArray)) { $dynamicArray[] = $value; }
Using these methods and principles, you can effectively and dynamically fill a PHP array based on any set of conditions or data sources.
#PHPDevelopment#DynamicArrays#WebDevelopment#ProgrammingTips#DataHandling#PHPArrays#BackEndDevelopment#CodingBestPractices#WebProgramming#DatabaseIntegration#vinhjacker#mageplaza
0 notes
Text
0 notes
Text
0 notes
Text
MySQL Aggregate Query using CodeIgniter’s Query Builder
CodeIgniter’s Query Builder ORM has class methods for nearly any kind of database access/operation you can think of. In this post, I’ll cover some of the available methods for retrieving aggregate-level query results. The examples in this post map out Query Builder method chaining to produce results you would get from a raw MySQL query. Continue reading to see more… Image by Clker-Free-Vector-Images from Pixabay Self-Promotion: If you enjoy the content written here, by all means, share this blog and your favorite post(s) with others who may benefit from or like it as well. Since coffee is my favorite drink, you can even buy me one if you would like! MySQL Query prototyping When working on Back-end PHP code, I typically prototype out MySQL queries using either MySQL Workbench or phpMyAdmin. Once I have the correct query results, I then translate the MySQL query over to the PHP layer. For applications written in core PHP, I tend to use the PDO class. However, when using CodeIgniter 4 (which is my PHP framework of choice at this time), you can use any of these options: Query Builder class methods.Extend the CodeIgniter Model class, utilizing its helper methods.A combination of both.For the examples in this post, I will use Query Builder class methods which are specific for aggregate-level data. Aggregate Query Results using MySQL As a SQL-first type of developer, I can honestly say that SQL is my favorite programming language and I am comfortable writing MySQL queries. That being said, I do appreciate the usefulness of an ORM. In my particular instance, since I use the CodeIgniter framework, the combination of CodeIgniter’s Models and the Query Builder class makes querying quite easy, among other things. Here is one such case in which I had little trouble retrieving the same query results using CodeIgniter Query Builder class ORM methods, as opposed to a raw MySQL query. I don’t feel that one approach is better or more valid than the other. This is just my experience as I learn CodeIgniter and am exposed to the Query Builder class and the in-built Models functionality provided by the framework. Let’s review this MySQL query which retrieves aggregated data on some of the walking stats and metrics I am interested in: SELECT MIN(`ws`.`day_walked`) AS `oldest_day_walked`, MAX(`ws`.`day_walked`) AS `recent_day_walk`, SUM(`ws`.`cal_burned`) AS `total_calories_burned`, SUM(`ws`.`miles_walked`) AS `total_miles_walked`, COUNT(*) AS `number_of_walks`, `sw`.`brand_name`FROM `walking_stats` AS `ws`INNER JOIN `shoes_worn` AS `sw`ON `ws`.`shoe_id` = `sw`.`shoe_id`GROUP BY `sw`.`brand_name`ORDER BY `sw`.`brand_name` ASC; Nothing too extravagant. A typical query using SUM(), COUNT(), MIN(), and MAX() aggregate functions. The above query returns these results: MySQL aggregate query results. Aggregate Query Results using CodeIginiter Query Builder class methods But, is this type of query – and more importantly – the query results, easily reproduced using CodeIgniter 4’s Query Builder class methods? They absolutely are. Let’s visit this CodeIgniter method I have in a class which extends the CodeIgniter Model: CodeIgniter 4 Query Builder class aggregate methods. The 4 key Query Builder aggregate-type methods used in the above Model method are: selectMin() – Maps to: SELECT MIN(field_name) selectMax() – Maps to: SELECT MAX(field_name) selectSum() – Maps to: SELECT SUM(field_name) selectCount() – Maps to: SELECT COUNT(field_name) Rounding out with both groupBy() and orderBy() methods complete the query. (Note: All 4 of the methods accept an optional 2nd parameter used to rename the field. I think of this in the same context as aliasing a column in MySQL using the AS keyword. The shoeAnalytics() model method produces identical query results as the MySQL query version shown previously. Looking at them in the browser using PHP”s print_r() method, we can see all of the data is there: Array( [0] => stdClass Object ( [oldest_day_walked] => 2019-01-02 [recent_day_walked] => 2020-12-02 [total_calories_burned] => 9091.1 [total_miles_walked] => 87.76 [number_of_walks] => 35 [brand_name] => Keen Koven WP ) [1] => stdClass Object ( [oldest_day_walked] => 2019-02-01 [recent_day_walked] => 2020-12-20 [total_calories_burned] => 1243.5 [total_miles_walked] => 13.25 [number_of_walks] => 5 [brand_name] => Keen Targhee Vent ) [2] => stdClass Object ( [oldest_day_walked] => 2019-07-15 [recent_day_walked] => 2020-05-13 [total_calories_burned] => 36805.2 [total_miles_walked] => 363.35 [number_of_walks] => 114 [brand_name] => Merrel MOAB Edge 2 ) [3] => stdClass Object ( [oldest_day_walked] => 2019-02-15 [recent_day_walked] => 2019-04-08 [total_calories_burned] => 404.7 [total_miles_walked] => 3.99 [number_of_walks] => 2 [brand_name] => New Balance Trail Runners-All Terrain ) [4] => stdClass Object ( [oldest_day_walked] => 2019-07-30 [recent_day_walked] => 2021-02-17 [total_calories_burned] => 21754.4 [total_miles_walked] => 216.61 [number_of_walks] => 75 [brand_name] => Oboz Cirque Low ) [5] => stdClass Object ( [oldest_day_walked] => 2020-05-24 [recent_day_walked] => 2020-12-04 [total_calories_burned] => 31222.5 [total_miles_walked] => 308.09 [number_of_walks] => 105 [brand_name] => Oboz Sawtooth II Low �� ) [6] => stdClass Object ( [oldest_day_walked] => 2019-01-01 [recent_day_walked] => 2019-08-08 [total_calories_burned] => 33084.5 [total_miles_walked] => 327.59 [number_of_walks] => 137 [brand_name] => Oboz Sawtooth Low ) [7] => stdClass Object ( [oldest_day_walked] => 2020-10-05 [recent_day_walked] => 2020-10-11 [total_calories_burned] => 1172.3 [total_miles_walked] => 11.42 [number_of_walks] => 4 [brand_name] => Skechers Crossbar )) Consider making a small donation on my behalf as I continue to provide useful and valuable content here on my site. Thank you. The shoeAnalytics() method can now provide these specific query results to any Views or libraries needing the data. Other CodeIgniter Query Builder class methods Which CodeIgniter Query Builder class methods do you find map nicely to a corresponding similar SQL expression? Which are those that do not map so nicely? Let me know in the comments! Similar Reading Visit any of the below PHP-related blog posts I have written if you are so inclined. Please share them with others who would benefit from the content as well. PHP date() function for common date formats PHP trim functions: trim, rtrim, and ltrim PHP empty() function use with MySQL NULL Use MySQL BLOB column with PHP to store .pdf file CodeIgniter Form Helper library – at a glance Like what you have read? See anything incorrect? Please comment below and thank you for reading!!! A Call To Action! Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well. Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients. To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…) Be sure and visit the “Best Of” page for a collection of my best blog posts. Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters. Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, are performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own. Have a look at all Apress PHP books and eBooks. The post MySQL Aggregate Query using CodeIgniter’s Query Builder appeared first on Digital Owl's Prose. https://joshuaotwell.com/mysql-aggregate-query-using-codeigniters-query-builder/
1 note
·
View note
Text
Enviar una campaña de MailChimp desde PHP
Enviar una campaña de MailChimp desde PHP aparece primero en nuestro https://jonathanmelgoza.com/blog/enviar-una-campana-de-mailchimp-desde-php/
Veremos un ejemplo sobre cómo enviar una campaña de MailChimp desde PHP para integrarlo en nuestros proyecto web de clientes o propios, te mostraremos código para obtener listas de suscriptores, obtener plantillas predefinidas y varias cosillas más relacionadas con la integración PHP con MailChimp.
Hace poco tuve la necesidad de Integrar MailChimp con PHP.
Afortunadamente MailChimp ofrece una excelente API y una aun mejor documentación por lo que no fue tan complicado conectar ambos.
Ya hemos hablado antes en este blog cómo obtener listas de MailChimp con PHP y ahora seguiremos adelante con este tema.
Lo más importante de este primer post es sin lugar a dudas la función para comunicarse con MailChimp.
Hoy veremos cómo enviar una campaña de MailChimp desde PHP para lo cual haremos varias cosas.
Antes que nada repasaremos la función para conectar a MailChimp para los que no han ido al post anterior.
Posteriormente también repasaremos el código para obtener tus listas de suscriptores en un combo.
Adicional a esto veremos también cómo:
Obtener miembros de una lista
Obtener etiquetas en la que esta un miembro
Obtener plantillas de correo predefinidas por nosotros
Crear una nueva campaña
Enviar una campaña
Antes que nada recuerda que debes de contar con una cuenta en MailChimp y obtener una API KEY para poder vincular.
Conectar con MailChimp desde PHP
function conectar_a_mailchimp( $url, $peticion, $api_key, $data = array() ) if( $peticion == 'GET' ) $url .= '?' . http_build_query($data); $mch = curl_init(); $headers = array( 'Content-Type: application/json', 'Authorization: Basic '.base64_encode( 'user:'. $api_key ) ); curl_setopt($mch, CURLOPT_URL, $url ); curl_setopt($mch, CURLOPT_HTTPHEADER, $headers); curl_setopt($mch, CURLOPT_RETURNTRANSFER, true); curl_setopt($mch, CURLOPT_CUSTOMREQUEST, $peticion); curl_setopt($mch, CURLOPT_TIMEOUT, 200); curl_setopt($mch, CURLOPT_SSL_VERIFYPEER, false); if( $peticion != 'GET' ) curl_setopt($mch, CURLOPT_POST, true); curl_setopt($mch, CURLOPT_POSTFIELDS, json_encode($data) ); return curl_exec($mch);
A partir de aquí toda referencia a la variable $API_KEY hace referencia a la clave del API requerida.
Obtener listas de suscriptores
$data = array( 'fields' => 'lists', 'count' => 5 ); $url = 'https://' . substr($API_KEY,strpos($API_KEY,'-')+1) . '.api.mailchimp.com/3.0/lists/'; $result = json_decode( conectar_a_mailchimp( $url, 'GET', $API_KEY, $data) ); if( !empty($result->lists) ) echo '<select>'; foreach( $result->lists as $list ) echo '<option value="' . $list->id . '">' . $list->name . ' (' . $list->stats->member_count . ')</option>'; echo '</select>'; elseif ( is_int( $result->status ) ) echo '<strong>' . $result->title . ':</strong> ' . $result->detail;
Obtener miembros de una lista
$data = array( 'offset' => '0', 'count' => '2000' ); $url = 'https://' . substr($API_KEY,strpos($API_KEY,'-')+1) . '.api.mailchimp.com/3.0/lists/[IDLISTA]/members/'; $result = json_decode( conectar_a_mailchimp( $url, 'GET', $API_KEY, $data) ); if( !empty($result->members) ) echo '<select>'; foreach( $result->members as $member ) echo '<option value="' . $member->id . '">' . $member->email_address . '</option>'; echo '</select>'; elseif ( is_int( $result->status ) ) echo '<strong>' . $result->title . ':</strong> ' . $result->detail;
Asegúrate de incluir el ID de tu lista, los IDs los obtuvimos con el código anterior.
Obtener etiquetas en la que esta un miembro
$data = array( 'offset' => '0', 'count' => '50' ); $url = 'https://' . substr($API_KEY,strpos($API_KEY,'-')+1) . '.api.mailchimp.com/3.0/lists/[IDLISTA]/members/[IDMIEMBRO]/'; $result = json_decode( conectar_a_mailchimp( $url, 'GET', $API_KEY, $data) ); echo '<select>'; echo '<option value="0">Seleccionar Tag</option>'; if( $result->tags_count > 0 ) for($i=0;$i<$result->tags_count;$i++) echo "<option value='" . $result->tags[$i]->id . "'>" . $result->tags[$i]->name . "</option>"; echo '</select>';
Aquí también debes de cambiar el ID de lista y el ID de miembro, ambos los obtenemos en los combos anteriores.
Obtener plantillas de correo predefinidas por nosotros
$data = array( 'offset' => '0', 'count' => '50', 'type' => 'user' ); $url = 'https://' . substr($API_KEY,strpos($API_KEY,'-')+1) . '.api.mailchimp.com/3.0/templates/'; $result = json_decode( conectar_a_mailchimp( $url, 'GET', $API_KEY, $data) ); echo '<select>'; echo '<option value="0">Seleccionar Template</option>'; if( $result->total_items > 0 ) for($i=0;$i<$result->total_items;$i++) echo "<option value='" . $result->templates[$i]->id . "'>" . $result->templates[$i]->name . "</option>"; echo '</select>';
Aquí obtenemos las plantillas de correo disponibles únicamente creadas por nosotros, para ver todas elimina ‘type’ => ‘user’.
Crear una nueva campaña
$subject = "Asunto"; $reply_to = "[email protected]"; $from_name = "Mi empresa"; $campaign_id = ""; $data = array( "recipients" => array( "list_id" => "[IDLISTA]", "segment_opts" => array( "saved_segment_id" => [IDETIQUETA] )), "type" => "regular", "settings" => array("subject_line" => $subject, "reply_to" => $reply_to, "from_name" => $from_name ) ); $url = "https://" . substr($API_KEY,strpos($API_KEY,"-")+1) . ".api.mailchimp.com/3.0/campaigns/"; $create_campaign = json_decode(conectar_a_mailchimp( $url, "POST", $API_KEY, $data )); $idCampaña = 0; if ( $create_campaign ) if ( ! empty( $create_campaign->id ) && isset( $create_campaign->status ) && "save" == $create_campaign->status ) $idCampaña = $create_campaign->id;
Sustituimos IDLISTA e IDETIQUETA para crear una campaña para una lista de suscriptores pero además para únicamente los que tengan dicho ID de Segmento, eliminar esta linea para enviar a toda la lista.
La campaña se crea como borrador pero aún no se envia.
Enviar una campaña
$data = array(); $url = "https://" . substr($API_KEY,strpos($API_KEY,"-")+1) . ".api.mailchimp.com/3.0/campaigns/".$idCampaña."/actions/send/"; $send_campaign = json_decode(conectar_a_mailchimp( $url, "POST", $API_KEY, $data )); print_r($send_campaign); if ( empty( $send_campaign ) ) echo "Se ha enviado la campaña"; elseif( isset( $send_campaign->detail ) ) $error_detail = $send_campaign->detail;
Con ayuda del IDCAMPAÑA creado en el paso anterior enviamos la campaña.
Como puedes ver enviar una campaña de MailChimp desde PHP no es complicado de hacer.
Puedes consultar más información sobre el API de MailChimp para aprender a hacer más cosas.
Espero y posteriormente seguir agregando más funcionalidades cómo agregar y eliminar suscriptores desde PHP.
Si esta información sobre cómo enviar una campaña de MailChimp desde PHP te fue de utilidad no olvides compartirla en tus redes sociales o dejarnos un comentario en la sección de abajo para aclararte cualquier duda relacionada al tema.
Hasta luego!
2 notes
·
View notes
Text
Json decode
#JSON DECODE HOW TO#
#JSON DECODE CODE#
#JSON DECODE FREE#
With the help of the Online JSON Parser Tool, we can easily format our minify JSON Data and easily find key and value pairs and identify changes quickly.
JSON Data mainly used when we need to transfer data with different platforms and it’s easy to synchronize and used in any system.
All Data are available in Key and value pair. Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the.
Here, In the above sample JSON data Name, Country, and Age are known as key and Jone, USA, and 39 known as a Value.
In Treeview, You can Search and highlight, and Sorting Data.
jsondecode converts JSON data types to the MATLAB data types in this table.
Minify or Compact JSON Data to resave and reduct its Size. JSON supports fewer data types than MATLAB.
JSON Validator for your Online Changes and your other JSON Data.
Redo and Undo facility when you edit your JSON online.
#JSON DECODE HOW TO#
How to Parse Large JSON Data with Isolates in Dart 2.The JSON Parser Tools have Below the main functionality:.
#JSON DECODE CODE#
How to Parse JSON in Dart/Flutter with Code Generation using FreezedĪnd if you need to parse large JSON data, you should do so in a separate isolate for best performance.In such cases, code generation is a much better option and this article explains how to use it: If you have a lot of different model classes, or each class has a lot of properties, writing all the parsing code by hand becomes time-consuming and error-prone. Restaurant Ratings example - JSON Serialization code.While the example JSON we used as reference wasn't too complex, we still ended up with a considerable amount of code: consider using the deep_pick package to parse JSON in a type-safe way.for nested JSON data (lists of maps), apply the fromJson() and toJson() methods.add explicit casts, validation, and null checks inside fromJson() to make the parsing code more robust.create model classes with fromJson() and toJson() for all domain-specific JSON objects in your app.When null, JSON objects will be returned as. When true, JSON objects will be returned as associative array s when false, JSON objects will be returned as object s. PHP implements a superset of JSON as specified in the original RFC 7159. use jsonEncode() and jsonDecode() from 'dart:convert' to serialize JSON data This function only works with UTF-8 encoded strings.But if we want our apps to work correctly, it's very important that we do it right and pay attention to details: JSON serialization is a very mundane task. You can build anything with Appwrite! Click here to learn more. Appwrite is a secure, self-hosted solution that provides developers with a set of easy-to-use REST APIs to manage their core backend needs. Open-Source Backend Server for Flutter Developers. Help me keep it that way by checking out this sponsor:
#JSON DECODE FREE#
Serializing Nested ModelsĪs a last step, here's the toJson() method to convert a Restaurant (and all its reviews) back into a Map:Ĭode with Andrea is free for everyone. You need to write the parsing code that is most appropriate for your use case. This specific implementation makes some assumptions about what may or may not be null, what fallback values to use etc.
if the reviews are missing, we use an empty list ( ) as a fallback.
map() operator to convert each dynamic value to a Review object using omJson()
the values in the list could have any type, so we use List.
the reviews may be missing, hence we cast to a nullable List.
1 note
·
View note
Text
jQuery Dependent DropDown List – States and Districts Using PHP-PDO
In this tutorial, we are going to learn how to change the district dropdown list option based on the selected state name using PHP-PDO.
In this example, we have two dropdowns for listing states and districts. On changing states drop-down values, the corresponding district dropdown values will be loaded dynamically using jQuery AJAX.
Click: https://phpgurukul.com/jquery-dependent-dropdown-list-states-and-districts-using-php-pdo/
File structure for this tutorial
config.php — Database connection file.
index.php — Main file having drop down
get_district.php — used to retrieve the district based on the selected state name.
MySQL Database structure for this tutorial
In this tutorial two MySQL Database table is used.
state
district
state table structure
CREATE TABLE `state` (
`StCode` int(11) NOT NULL,
`StateName` varchar(150) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
district table structure
CREATE TABLE `district` (
`DistCode` int(11) NOT NULL,
`StCode` int(11) DEFAULT NULL,
`DistrictName` varchar(200) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Step 1: Create a database connection file (config.php)
<?php
// DB credentials.
error_reporting(0);
define(‘DB_HOST’,’localhost’);
define(‘DB_USER’,’root’);
define(‘DB_PASS’,’’);
define(‘DB_NAME’,’demos’);
// Establish database connection.
try
{
$dbh = new PDO(“mysql:host=”.DB_HOST.”;dbname=”.DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => “SET NAMES ‘utf8’”));
}
catch (PDOException $e)
{
exit(“Error: “ . $e->getMessage());
}
?>
Step2: Create a HTML form with two fields . One is for state and another one is for district.
<form name=”insert” action=”” method=”post”>
<table width=”100%” height=”117" border=”0">
<tr>
<th width=”27%” height=”63" scope=”row”>Sate :</th>
<td width=”73%”><select onChange=”getdistrict(this.value);” name=”state” id=”state” class=”form-control” >
<option value=””>Select</option>
<! — — Fetching States — ->
<?php
$sql=”SELECT * FROM state”;
$stmt=$dbh->query($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row =$stmt->fetch()) {
?>
<option value=”<?php echo $row[‘StCode’];?>”><?php echo $row[‘StateName’];?></option>
<?php }?>
</select></td>
</tr>
<tr>
<th scope=”row”>District :</th>
<td><select name=”district” id=”district-list” class=”form-control”>
<option value=””>Select</option>
</select></td>
</tr>
</table>
</form>
Step3: Getting States using jQuery AJAX
This script contains a function that will be called on changing state dropdown values. It will send AJAX request to a PHP page to get corresponding district dropdown options.
<script>
function getdistrict(val) {
$.ajax({
type: “POST”,
url: “get_district.php”,
data:’state_id=’+val,
success: function(data){
$(“#district-list”).html(data);
}
});
}
</script>
Step 4: Read the district table using PHP based on the selected state name.
This PHP code connects the database to retrieve district table values based on the state id passed by jQuery AJAX call.
<?php
require_once(“config.php”);
if(!empty($_POST[“state_id”]))
{
$stateid=$_POST[“state_id”];
$sql=$dbh->prepare(“SELECT * FROM district WHERE StCode=:stateid”);
$sql->execute(array(‘:stateid’ => $stateid));
?>
<option value=””>Select District</option>
<?php
while($row =$sql->fetch())
{
?>
<option value=”<?php echo $row[“DistrictName”]; ?>”><?php echo $row[“DistrictName”]; ?></option>
<?php
}
}
?>
How to run this script
1.Download the zip file
2.Extract the file and copy statedistdropdown-pdo folder
3.Paste inside root directory(for xampp xampp/htdocs, for wamp wamp/www, for lamp var/www/html)
4.Open PHPMyAdmin (http://localhost/phpmyadmin)
5.Create a database with name demos
6.Import regdb.sql file(given inside the zip package )
7.Run the script http://localhost/statedistdropdown-pdo
PHP Gurukul
Welcome to PHPGurukul. We are a web development team striving our best to provide you with an unusual experience with PHP. Some technologies never fade, and PHP is one of them. From the time it has been introduced, the demand for PHP Projects and PHP developers is growing since 1994. We are here to make your PHP journey more exciting and useful.
Website : https://phpgurukul.com
0 notes
Text
Laravel 9 Elasticsearch Integration From Scratch With Example
In this post, we'll talk about how to incorporate Elasticsearch from scratch using a Laravel 9 example. Full-text search engine Elasticsearch is deployed in real-time and has multitenant support. It offers a JSON document format and an HTTP web interface.
Table of Content
Step 1: Install Elasticsearch Step 2: Create Table using migration Step 3: Install Package Step 4: Add providers and aliases Step 5: Create Route Step 6: Create a Model and Controller Step 7: Create Blade Files Step 8: Run Our Laravel Application
Step 1: Install Elasticsearch
Elasticsearch will be installed in our system; if you haven't downloaded it yet, click here for instructions.
Step 2: Create Table using migration
We must now start a migration. In order to construct the student's table migration, we will use the command below. php artisan make:migration create_students_table --create=students upon successful migration. The database/migrations/create students table file needs to be modified as shown below. Once the aforementioned file has been modified, run the command below. php artisan migrate
Step 3: Install Package
Installing the elasticquent/elasticquent package will now be done. Consequently, first enter composer.json and add the line below. "elasticquent/elasticquent": "dev-master"
Step 4: Add providers and aliases
In the "config/app.php" section, we will add the providers and aliases listed below. 'providers' => , 'aliases' => We will now run the following command to create an elastic search configuration file.
Step 5: Create Route
In the "routes/web.php" file, add the following route code.
Step 6: Create a Model and Controller
The commands listed below assist in creating the controller and model. php artisan make:controller StudentController php artisan make:model Student Student.php StudentController.php
Step 7: Create Blade Files
In the "resources/views/" folder directory, we will create a student-search file and paste the code below. student-search.blade.php @extends('layouts.app') @section('content')
Laravel 7 Elasticsearch integration from scratch with example
{{ Form::open(array('method'=>'get','class'=>'')) }} Go! {{ Form::close() }} @if(!empty($students)) @foreach($students as $key => $value) {{ $value }}
{{ $value }}
{{ $value }} @endforeach @endif Create New Student @if (count($errors) > 0) Whoops! There were some problems with your input. @foreach ($errors->all() as $error) - {{ $error }} @endforeach @endif {{ Form::open(array('url' => 'StudentSearchCreate','autocomplete'=>'off')) }} First Name: {{ Form::text('first_name', null, array('placeholder' => 'First Name','class' => 'form-control')) }} Last Name: {{ Form::text('last_name', null, array('placeholder' => 'Last Name','class' => 'form-control')) }} Address: {{ Form::text('address', null, array('placeholder' => 'Address','class' => 'form-control')) }} Submit {{ Form::close() }} @endsection
Step 8: Run Our Laravel Application
The command listed below can be used to launch the server and run this example. php artisan serve Now, we'll execute our example by navigating to the URL listed below in a browser. http://127.0.0.1:8000/studentSearch Read the full article
0 notes
Text
How do you fill a PHP array dynamically (PHP, array, development)?
To dynamically fill a PHP array, you can use various methods to add elements to the array during runtime. Here are some common approaches:
Using array_push() function:
The array_push() function allows you to add one or more elements to the end of an array.
phpCopy code
$myArray = array(); // Initialize an empty array
// Dynamically add elements to the array array_push($myArray, "Element 1"); array_push($myArray, "Element 2"); array_push($myArray, "Element 3");
// Resulting array: ["Element 1", "Element 2", "Element 3"]
Using square brackets:
You can also use square brackets to add elements directly to the array.
phpCopy code
$myArray = array(); // Initialize an empty array
// Dynamically add elements to the array $myArray[] = "Element 1"; $myArray[] = "Element 2"; $myArray[] = "Element 3";
// Resulting array: ["Element 1", "Element 2", "Element 3"]
Associative array:
For associative arrays, you can set values dynamically by specifying the key.
phpCopy code
$myArray = array(); // Initialize an empty associative array
// Dynamically add elements to the array $myArray["name"] = "John"; $myArray["age"] = 30; $myArray["email"] = "[email protected]";
// Resulting array: ["name" => "John", "age" => 30, "email" => "[email protected]"]
Using loop:
You can use a loop to dynamically populate the array with elements.
phpCopy code
$myArray = array(); // Initialize an empty array
// Use a loop to add elements to the array for ($i = 1; $i <= 5; $i++) { $myArray[] = "Element " . $i; }
// Resulting array: ["Element 1", "Element 2", "Element 3", "Element 4", "Element 5"]
These methods allow you to dynamically add elements to a PHP array during development, making your code flexible and adaptable to various data requirements.
#PHP#Array#Dynamic Array#Array Manipulation#Array Functions#PHP Development#PHP Programming#Web Development#Code Examples.#vinhjacker#mageplaza
1 note
·
View note
Text
Why do I like CakePHP so much? And so would you!
I've tried a few PHP frameworks over the last year and a half, including CakePHP, Laravel, Silex, and Phalcon. CakePHP framework is my favourite of all of them.
It is difficult for a newbie to learn CakePHP. It is difficult to get started at first. CakePHP necessitates perseverance. CakePHP has a high learning curve that gets linear with time but never becomes steady (You always learn something new).
But wait a minute, after a while, coding with CakePHP seems like A PIECE OF CAKE.
M for Model runs the company.
V for View represents the data to the client.
C for Controller manages the client request and aids in communication between the model and the view.
Listed below are a few CakePHP features that help this Framework stand out.
1. Preference for Convention over Configuration
CakePHP favours convention over configuration, which implies that there are a few rules that must be observed while using CakePHP. Although you may wonder what is going on, in the long run they assist a lot and dramatically save the time it would take to administer your application.
2. Model of Inheritance
CakePHP has an excellent inheritance structure, with reusable functions preserved in the parent class and class-specific functions kept in the child class. If you have a method that only retrieves a certain field from the database, place it in the AppModel if it is used by many classes i.e. Model, and if the function is shared by several controllers, place it in the AppController.
3. Configuration Based on the Environment
Every application needs a unique set of setups, namely the production and development environments. To do this with CakePHP, create a separate file called config.php that contains all of the fundamental settings and API keys, and then import this file into your application's core.php file as follows:
Load Configure::config.php('config.php', 'default');
CakePHP development also includes two files that are relevant to your local machine environment, database.php and email.php.
4. Functions for saving data
CakePHP save methods are simple to use and allow you to choose between updating an existing record and generating a new one based on the value of the ID key.
Save works by referring to the model's schema and creating a sample model structure with their default values (it only uses those with default values), and then replacing those values with the data passes.
When you pass an empty array to the method, there is a minor catch. So, if an empty array is supplied, the save method will operate correctly and will return a proper answer, but an empty row will be generated in your table.
5. Before/after callbacks (SAVE, FIND, FILTER, VALIDATE)
The callbacks provided by CakePHP are one of the nicest things I discovered and enjoy about it. Both the Controllers and the Models have callbacks that are invoked in a certain order. For example, in your application, the controller will handle the requests that your application receives. Each request must be validated, and CakePHP provides the beforeFilter callback (which is called before any request reaches the desired endpoint). The beforeFilter function provides the best ground to authenticate and authorise each request as it is. Similarly, beforeFind allows you to specify a few default criteria before every save.
Note: When utilising update functions, the callbacks are not automatically invoked, therefore you must explicitly invoke them.
6. Scheduling
CakePHP provides a convenient method for routing requests to a Controller Endpoint. It includes a second file (routes.php) in which you may define all of the routes, as well as a list of custom routes. Furthermore, using routes, you may have api versioning utilising CakePHP prefixing. It also includes a default set of rest-routes that you can use to get your application up and running.
7. Bake Module – Generate Code Automatically
CakePHP's Bake console is another another effort to get you up and running with CakePHP services as quickly as possible. The Bake console may generate any of CakePHP's fundamental components, including models, views, and controllers. Bake can develop a completely working application in only a few minutes, not just skeleton classes. In fact, after scaffolding an application, Bake is a natural next step.
8. Find
CakePHP has a Find method that is simple to use and comprehend. This function's purpose is to conduct READ operations on your database and obtain data from it. By including the FIND function, you may avoid writing several sorts of SQL queries, such as repeated fetching, establishing a View, or executing a Join. CakePHP guarantees that you utilise the FIND function and leave the rest to the CakePHP ORM, which will create the query and provide the data in the suitable manner.
9. Elements and Behaviors
CakePHP has a set of Plug and Play packages known as Components and Behaviours, which are utilised in the Controllers and Models, respectively. If you believe that a big amount of the code you use is the same and can be reused to the point where various projects may use it, then Components and Behaviours are an excellent fit. Components allow Controllers to share code, and Behaviours let Models to do the same. Assume you are currently utilising Type A authentication to validate requests and want to switch to Type B. You simply need to replace Type A components in your controller with Type B components (Considering Authentication was done using a Component)
There are other more aspects of CakePHP that may be discussed, such as its ORM, sanitization, ACL, caching, and so on. But keep it brief. I hope that after reading this, you have a better understanding of how CakePHP may benefit you and are eager to test it out.
0 notes
Text
Best Online Coding School
When the pandemic hit the globe, getting to know coding at domestic have become a medium of turning creativeness into truth for youngsters. Kids in recent times can without problems examine the artwork of programming, coding, software program development, net development, or even Python programming language, that too from the very starting simply through genuinely enrolling themselves on diverse online programmers.
This is call for getting to know coding and programming is foresee to boom within-side the destiny and it calls for an eagerness in youngsters as properly to upward push and shine on this precise field. We have curate a listing of pinnacle five systems which might be specialized in coaching one of the maximum vital talents to assist each youngster and adults examine the present day programming language.
Various best online coding schools for kids are as follows:
CodeKaroYaaro: CodeKaroYaaro is an internet coding college supplying e-particularly designed publications for children from 6 to fifteen years of age. Gone are the times whilst one out of some fifty humans knew approximately computers. Nowadays, the whole thing isn’t any much less than a rat race and era has turn out to be one of the conditions to transport beforehand in life. It is excessive time to train and familiarize children with the standards that power the modern day era. You ought to have certainly heard how programming initiates new improvements within-side the technical domain. What higher manner for our kids to recognize why and the way the era round them operates than through studying to code and adapting to the era round them.
Udemy: Udemy is some other relied on platform wherein you'll locate greater than 800 guides, all committed to make you a seasoned at coding. Python, JavaScript, WordPress, HTML, CSS, Android Development, Bootstrap, PHP, Swift, you call something and the internet site gives a number of the first-class loose guides on this domain. Not best this, the unexpected reality is that IT aficionados can really educate the thoughts in their youngsters within-side the area of coding at a completely early age.
Coursera: When we communicate approximately on line guides, Coursera is typically the primary alternative that moves the thoughts of the learners. With an array of famous and area of interest guides, Coursera gives latest curriculum and school help to the aspirants. With extra than 250 guides dealing most effective withinside the programming languages, you may now no longer go back empty-surpassed when you make your thoughts to pursue a route in Coding from Coursera. You can select route language, level, duration, precise skills, and mode of gaining knowledge of relying upon your requirement.
WhiteHat Jr.: Founded in 2018, WhiteHat Jr is an ed-tech platform that teaches college students coding via one-on-one video training with instructors. WhiteHat Jr gives AI publications for kids elderly six to fourteen years. The app facilitates kids study laptop programming and encourages them to create games, animations, applications, and more. The platform works with a stay one-on-one on line coaching layout and a very well researched curriculum.
0 notes
Text
So I was talking to an old co-worker about how to approach PHP sessions (and how to keep users from taking over other users’ sessions) and I realized that he and I have a very similar bad habit of using $_SESSION as a shortcut for declaring variables as global because it’s a super global array that is essentially useless in a secure application.
So that this isn’t entirely gibberish to people who don’t PHP, $_GET, $_POST, and $_SESSION are all “user input” super global arrays, meaning they are available to all code no matter how it is nested or constructed.
$_GET & $_POST are directly user accessible, as they are intended to store user navigation and form variables respectively (but developers sometimes abuse both for other purposes). So they are usually treated with a lot of suspicion by developers. Most users are good faith, but there’s a lot of money in breaking websites, so you have to make sure what you are working with is in the form you’re expecting it to be and not dangerous to perform whatever operation or storage with.
$_SESSION is not usually directly user accessible, but it is designed to allow applications to have some persistent variables between discrete requests. If you haven’t heard me say it before, PHP is a stateless programming language. Every page you visit, every action you take, is a new PHP process that has no access to information about any previous processes. Because this persistence isn’t the normal behavior, you also have to treat it with some suspicion and ensure it is what you expect it to be. Add to that the complication that in some situations you can actually store these variables in the cookies saved on the client machines (which of course means users can edit them), and it’s easy to see why you might want to put it entirely to the side if you have something else to rely on, like a database.
So, long story short, in my current development projects. All I use sessions for is linking activity up with the database, ensuring a user can’t resume the same session from a different device, and seeing if a particular session has logged in/been active in the activity window, and for the application to notify itself that it needs to notify the user of something.
Which means there’s this superglobal sitting there mostly empty. So on application start I dump a bunch of variables from the database into it that I will probably need to access over and over from various parts of the application.
This is a bad habit because it’s not what $_SESSION is for, and because it breaks the idea that my framework minimizes the amount of total work done by ensuring that no work that isn’t immediately used is done in any particular request, but it’s how my terrible boss who “taught” me PHP used it and I never really got out of the habit.
1 note
·
View note