PHP & Web Development Blogs

Search Results For: class
Showing 1 to 5 of 27 blog articles.
1592 views · 8 months ago


Introduction


MongoDB, a popular NoSQL database, provides flexibility and scalability for modern web applications. In this guide, we will explore how to use MongoDB with PHP, a widely used scripting language. We'll cover the necessary steps to establish a connection, perform CRUD operations, and leverage the power of MongoDB in your PHP projects.

Prerequisites


Before diving into MongoDB integration, ensure you have the following:
   
. MongoDB installed and running on your machine.
   
. PHP installed on your machine, preferably version 7 or above.
   
. Composer, a dependency management tool for PHP.

Step 1: Installing the MongoDB PHP Driver


The first step is to install the MongoDB PHP driver, which enables PHP to communicate with MongoDB. We can use Composer to handle the installation process efficiently. Open your terminal or command prompt and navigate to your project directory. Then run the following command:


composer require mongodb/mongodb


This command installs the MongoDB PHP driver along with its dependencies. Composer will create a vendor directory containing the required files.

Step 2: Establishing a Connection


To connect to MongoDB from PHP, we need to create a new instance of the MongoDB client class. Open your code editor and create a new PHP file, for example, connect.php. Add the following code:


<?php

require 'vendor/autoload.php';

use MongoDB\Client;

$client = new Client("mongodb://localhost:27017");

?>


In this code, we require the Composer-generated autoloader and import the Client class. We then create a new instance of the Client class, specifying the MongoDB server's connection URL. Adjust the URL if your MongoDB server is running on a different host or port.

Step 3: Performing CRUD Operations


Now that we have established a connection, let's explore how to perform basic CRUD operations using MongoDB with PHP.

Creating Documents


To insert a new document into a MongoDB collection, use the insertOne() method. Here's an example:

<?php
$collection = $client->test->users;

$newUser = [
'name' => 'John',
'email' => '[email protected]',
'age' => 25
];

$insertResult = $collection->insertOne($newUser);
echo "Inserted document ID: " . $insertResult->getInsertedId();
?>


In this code, we select the users collection within the test database. We create a new document as an associative array and then use the insertOne() method to insert it into the collection. Finally, we retrieve and display the ID of the inserted document using the getInsertedId() method.

Reading Documents


To retrieve documents from a MongoDB collection, use the find() method. Here's an example:

<?php
$collection = $client->test->users;

$documents = $collection->find();

foreach ($documents as $document) {
echo $document['name'] . ': ' . $document['email'] . "\n";
}
?>


In this code, we retrieve all the documents from the users collection. We iterate over the result using a foreach loop and access specific fields, such as the name and email, to display their values.

Updating Documents


To update documents in a MongoDB collection, use the updateOne() method. Here's an example:

<?php
$collection = $client->test->users;

$updateResult = $collection->updateOne(
['name' => 'John'],
['$set' => ['age' => 30]]
);

echo "Modified " . $updateResult->getModifiedCount() . " document(s).";
?>


In this code, we update the age field of the document with the name 'John' using the $set operator. The updateOne() method updates the first matching document. We then retrieve the number of modified documents using the getModifiedCount() method.

Deleting Documents


To remove documents from a MongoDB collection, use the deleteOne() method. Here's an example:

<?php
$collection = $client->test->users;

$deleteResult = $collection->deleteOne(['name' => 'John']);
echo "Deleted " . $deleteResult->getDeletedCount() . " document(s).";
?>


In this code, we delete the document with the name 'John'. The deleteOne() method removes the first matching document, and we retrieve the number of deleted documents using the getDeletedCount() method.

Conclusion


Congratulations! You have learned the basics of using MongoDB with PHP. By establishing a connection, performing CRUD operations, and leveraging the power of MongoDB, you can build powerful and scalable web applications. Remember to refer to the MongoDB PHP documentation for additional features and advanced usage.
5720 views · 2 years ago
A Beginners Guide To Artificial Intelligence For Web Developers

Artificial Intelligence has significantly transformed the way we work and interpret information. With technologies such as OCR, machine learning, deep learning, natural language processing, and computer vision; machines are now able to provide greater insights and perform tasks that typically required hours and hours of work from humans.

What is artificial intelligence?


A.I. or artificial intelligence is the technology that enables machines to perform tasks that usually require human intelligence. But instead of using human brains, A.I. uses different technologies such as computers, or even software algorithms, to perform tasks. Some of the most common A.I. technologies include speech recognition, voice recognition, machine translation, natural language processing, computer vision, and predictive analytics. The term artificial intelligence comes from the combination of artificial and intelligence. While artificial intelligence is a property of the physical world, intelligence is the property of the mind. How does it make sense in Web Development? As mentioned earlier, A.I. has significantly transformed the way we work and interpret information.

How is AI applied to web development?


In the majority of cases, AI is used to assist a developer in a number of functions: Automatically format existing content, analyze images for semantic meaning Break down complex tasks into smaller pieces Example applications of AI in web development Example image compression algorithms. Tools such as image recognition and machine learning have been key factors in the development of new image processing algorithms. Traditionally, manually processing an image was a lengthy and tedious process, but when computer vision was introduced into the process it drastically decreased the amount of time required to complete this task. Now, programs such as image recognition can identify objects in images and classify them based on both visual and metadata attributes.

Machine learning


When data is fed into a machine learning algorithm, the machine learns to understand it. For instance, if you provide a machine learning algorithm examples of dogs verses blueberries, the machine will learn to identify what a picture of a blueberry looks like, verses a picture of a dog. Natural Language Processing Natural language processing is a sub-field of machine learning. You can apply natural language processing for reading emails, chatting, or writing blog posts (such as this one!). A good example of natural language processing in action can be found in Microsoft's Cortana. Deep learning This is the most popular type of artificial intelligence today.

Deep learning


Deep learning algorithms are very similar to how the human brain works, with its built in mechanisms to learn and memorise a vast amount of information. It's these connections that enable machines to be able to recognise patterns and learn from them. An example of this is Google Translate, which recognises more than a 1,000 languages. This isn't an example of AI but it shows how useful these programs can be. Deep learning is one of the hottest technologies in the field of machine learning and this explains why almost all of the major technology companies are pushing these advances forward.

Natural language processing


For example, your phone can understand you better when you speak to it. If you say “Hey, Siri,” your phone will listen to you and respond to your questions. In general, it means that the system has been trained and is able to better understand the context of what you’re trying to communicate. This type of Natural Language Processing is used in the majority of companies today, including the likes of Google and Apple, to improve the user experience, provide better customer service, and to aid in the effective execution of processes. Machine learning Machine Learning is an extremely powerful technique used to further improve the knowledge of artificial intelligence, as well as to make machines smarter by discovering patterns and generalities in vast amounts of data.

Computer vision


Computer vision is a technology that has been able to recognize objects in images and video for eons. A popular example is Apple's Siri, which was one of the first software to use computer vision to provide contextual awareness. AI is built on this technology, providing the capability to recognize various images and videos. The industry is still in its infancy, but what we have seen so far has been incredibly incredible. What's amazing is that just a few years ago we thought that vision was completely under our control, but now, it has evolved to understand the nuances of objects.

Conclusion

“In the year 2050, the Amazon book you ordered for your Kindle will be delivered by a drone.”

This futuristic statement by Amazon CEO Jeff Bezos did leave you pondering. But it is one thing to dream about the future and another thing to think about the innovations taking place in the present and how you can exploit them to drive better business results. To make the most of the technologies coming to our everyday lives, we must acquire a knowledge of the AI technology, its features, and its application. Succeeding in today’s competitive and challenging business world, requires a broad set of skills such as coding, business analysis, computer programming, and ecommerce marketing.

Learn more about AI with our video library
8203 views · 3 years ago


Recently I was faced with a task to post data from a .csv file to an external REST API. I’m just going to log in to this article about what I did to get the job done.

Let’s start by creating a template for uploading the file. For this article’s sake, lets make the changes in the dashboard.blade.php file.


<form method="post" enctype="multipart/form-data"> @csrf <div class="custom-file"> <input type="file" accept=".csv" name="excel" class="custom-file-input" id="customFile" /> <label class="custom-file-label" for="customFile">Choose file</label > </div> <div> <button type="submit" class="btn btn-primary btn-sm" style="margin-top: 10px" >Submit> </div>

</form>

Note : Don’t forget to add enctype=”multipart/form-data”!



Once the user has submitted the file, we need a new router to process the file and send its content to the REST API. Let’s start by creating a Controller.


php artisan make:controller UploadController


Now in the web.php file,


Route::post('/upload', [UploadController::class, 'upload'])->name('upload')->middleware('auth');


In the UploadController.php , create a function named upload. We will be writing all the code inside this function. Also, we need an action for the form.


<form method="post" action="{{route('upload')}}" enctype="multipart/form-data">


Now inside the upload function, we need to get the submitted file and parse its contents.

Get the submitted file,


$file = $request->file('excel');


Parse the submitted file,


if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { ..... }

}


We will be using a dummy REST API to create users — https://reqres.in/api/users. This is the request body required to create a user.


{ "name": "test", "job": "test"

}


Keeping this in mind, we will create a sample .csv template to be submitted. The fields need to be two, namely Name and Job.



We need to send the values from this file as the request body to the API. So let’s add the code to loop through the content of this file.


if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { Http::post('https://reqres.in/api/users', [ 'name' => $data[0], 'job' => $data[1], ]); }

}


This will create each student for each row of the file. But we don’t need to send the data of the first row of the file.

Full code:


public function upload(Request $request){ $file = $request->file('excel'); if($file){ $row = 1; $array = []; if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { if($row > 1){ Http::post('https://reqres.in/api/users', [ 'name' => $data[0], 'job' => $data[1], ]); array_push($array,$data[0]); } $request->session()->flash('status', 'Users '.implode($array,", ").' created successfully!'); $row++; } } }else{ $request->session()->flash('error', 'Please choose a file to submit.'); } return view('dashboard');

}


This will post the data starting from the second row of the file, display a success message once the users are created, and an error message if the submit button is clicked without choosing a file.

Full template:


<div class="container max-w-7xl mx-auto sm:px-6 lg:px-8" style="width: 50%"> @if (session('status')) <div class="alert alert-success"> {{ session('status') }} </div> @endif @if (session('error')) <div class="alert alert-error"> {{ session('error') }} </div> @endif <form action="{{route('upload')}}" method="post" enctype="multipart/form-data"> @csrf <div class="custom-file"> <input type="file" accept=".csv" name="excel" class="custom-file-input" id="customFile" /> <label class="custom-file-label" for="customFile">Choose file</label> </div> <div> <button type="submit" class="btn btn-primary btn-sm" style="margin-top: 10px">Submit</button> </div> </form>

</div>




That’s it, thanks for reading :)
5245 views · 3 years ago
Top 12 PHP Libraries to Leverage Your Web App Development



PHP, by all means, is an immensely powerful language!



We may fall short of words, but there won't come any end to its qualities. The endless functionalities and possibilities of this server-side scripting language have managed to get it a strong and supportive community of PHP programmers on a global level. At present, PHP powers more than half on websites and applications on the internet.


Do you know what makes PHP so praiseworthy?



It is the simplicity, easy programming structure, and developer-friendly web functionalities that are to be credited to turn PHP into one of the top programming languages. You can create highly interactive and dynamic websites and applications with desired results by making use of PHP.



However, coding often could be a tough and tedious task to accomplish. As a solution to this, you get built-in PHP libraries that optimize the process of coding for maximum productivity.



But what are these libraries?




That's exactly what you will find out as you move ahead in this article, a list of top 12 PHP libraries capable of leading the development process in an intended manner.



So, without waiting any further, let's move ahead to learn about PHP libraries in-depth.



PChart




PChart is a PHP library assisting with the generation of text data in the form of something more appealing to the eyes and known as visual charts.



You can use this library to represent data as bar charts, pie charts, and many more different formats. The PHP script here utilizes SQL queries to put data in the impressive charts or graphs form.



Mink




Another well-known in the list of PHP libraries is Mink. It allows you to keep an eye on if a proper interaction is happening between your web apps and the browser. Eliminating the API differences between the two types of browser emulators, Mink offers an authentic testing environment for you. It also supports PHPUnit, Behat, and Symfony2.



Monolog




Monolog is a PHP logging library that helps you with saving logs to the specified locations by sending them to set files, sockets, inboxes, databases, or other web services. The use of the PSR-3 interface permits to type-hint logs in counter to your libraries that maintain optimum interoperability.



Hoa




This modular, extensible, and structured set of PHP libraries we know as Hoa establishes a link between the research and the industry.



It recommends essential paradigms, mechanisms, and algorithms for building the reliability of a site. Many PHP developers in different parts of the world use Hoa for ideal PHP development.



Guzzle




Guzzle is an HTTP client library for PHP that enables you to send HTTP requests to combine with web services.



It offers a simple interface that makes the development of query strings, POST requests, HTTP cookies, and many other attributes possible. You can also use Guzzle to send synchronous and asynchronous requests from the similar interface.



Ratchet




If your need is to develop real-time, two-directional apps between clients and servers over WebSockets, Ratchet is the PHP library you need to do it effectively.



Creating event-driven apps with Ratchet is a rapid, simple, and easy job to do!



Geocoder




Geocoder is a library to create applications that are very well geo-aware.



With Geocoder, there is an abstraction layer that helps with geocoding manipulations.



It is further split into two parts, known as HttpAdapter and Provider.



ImageWorkshop




ImageWorkshop is an open-source PHP library letting you work over the manipulation of images with layers. You can crop, resize, add watermarks, create thumbnails, and so much more. You can also enhance the images on the sites.



PhpThumb




phpThumb is the library specialized at handling the work associated with creating thumbnails with minimal coding. Accepting every image source type and image formats, it makes you do a lot ranging from rotating or cropping to watermarking or defining the image quality.



Parody




This simple library we know as Parody is used to copy classes and objects. It also provides results for method calls, acquiring properties, instantiating objects, and more. Sequential method chaining is used by Parody to produce defining class structures.



Imagine




This object-oriented PHP library is meant for working with images along with manipulating them. The often adopted operations such as resizing, cropping, and applying filters happen instantly and relatively well with Imagine.



With Imagine, you get a color class that forms the RGB values of any given color. Draw shapes like arc, ellipse, line, etc. with the features available.



PhpFastCache




PhpFastCache is an open-source PHP library that makes caching feasible. Coming as a single-file, it can be integrated within a matter of minutes.



Caching methods supported by PhpFastCache involve apc, memcache, memcached, wincache, pdo, and mpdo.


The Bottom Line




It's not about what extra difference these libraries make; it's about what significant individual contributions these libraries make for a final desired PHP app or website.



A PHP programmer, too, agrees with these libraries' benefits.



It's your time now to try and believe!
8122 views · 3 years ago


Welcome back! If you're new to this series have a look at Part 1 here

Today we are going to beef things up a bit and we will focus on the backend and some key CMS functionality.

It's time to get excited, this is where you'll start to see your barebones structure morph into something extraordinary!

Tired of my intro? That's ok! Let's jump into it!

Getting the DB on board


Before we delve into this, it's imperative that we take a minute and plan things out.

The database tables that are vital to any CMS are the menu, the user table, and the content table.

Our menu table will start of as follows:

CREATE TABLE 'mydbname'.'menus' ( 'ID' INT(11) NOT NULL AUTO_INCREMENT , 'menuname' VARCHAR(100) NOT NULL , 'item' VARCHAR(50) NOT NULL , 'itemlink' VARCHAR(100) NOT NULL , PRIMARY KEY ('ID')) ENGINE = MyISAM COMMENT = 'menu table';


Let's break this down a bit.

In the SQL above, we're creating a new table called menus.

Essentially our structure looks like this:

ID | Menuname | Item | Itemlink

Our ID field is our unique identifier (our PRIMARY KEY).

Tip: Remember, you can use raw SQL or a tool like PhpMyAdmin to create your db tables/execute SQL queries.

Next up is our user table.

CREATE TABLE 'mydbname'.'users' ( 'ID' INT(11) NOT NULL AUTO_INCREMENT , 'username' VARCHAR(100) NOT NULL , 'password' VARCHAR(50) NOT NULL , 'email' VARCHAR(100) NOT NULL , PRIMARY KEY ('ID')) ENGINE = MyISAM COMMENT = 'user table';


Visually represented this structure looks like this:

ID | Username | Password | Email

Our ID field is our unique identifier.

And finally, our content table modifications. You probably remember creating a rudimentary content table in Part 1 of the series.

ALTER TABLE 'mydbname'.'content' ADD content_type VARCHAR(50);


Yep, you guessed right, in the above statement we are altering our content table and adding a new field called content type.

Our new table structure now looks like this:

ID | Title | Content | Author | Content Type

Planning to Add to the Backend


Next , we're going to add a menu section, an add user section, and we'll also modify our content section.

Let's do this! reate a file called menus.php in your backend folder.

Next, code a HTML form to save your menu data.

The form needs the following fields:

Menu Name (we called this menuname in our db table).

Menu Item Name (we called this item in our db table).

Menu Link (we called this itemlink in our db table).

Try to follow Part 1 to do this on your own.

If you get a little stuck, that's ok. You can also follow the example below:

<form method="post" action="<?php $_SERVER['PHP_SELF'];?>"/>

<input type="text" name="menuname" class="mytextbox" placeholder="Menu Name" required />

<input type="text" name="item" class="mytextbox" placeholder="Item" required />

<input type="text" name="itemlink" class="mytextbox" placeholder="Item Link" required />

<input type="submit" value="Save Menu Item" name="savemenu" class="mybutton"/>

</form>


Notice the use of CSS classes? The gravy!

This will come in handy in our next tutorial.

Next, let's add the form processing code as we need to save these fields to the database. Remember to use the sanitization technique you learned in Part 2.

Add this above your <form> tag.

<?php

if(isset($_POST['savemenu'])){

include('../includes/conn.php');

if ($letsconnect->connect_error) {

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

}else{

$menuname = $letsconnect ->real_escape_string($_POST['menuname']);

$item = $letsconnect -> real_escape_string($_POST['item']);

$itemlink = $letsconnect->real_escape_string($_POST['itemlink']);

$sql = "INSERT INTO menus(menuname,item,itemlink) VALUES ('".$menuname."', '".$item."', '".$itemlink."')";

if (mysqli_query($letsconnect, $sql)) {

echo "Your data was saved successfully!";

} else { echo "Error: " . $sql . "" . mysqli_error($letsconnect);

} $letsconnect->close();

}

}

?>


Ok phew, the menu data capturing section is done.

Let's move on to the user data capturing section, and modify the content capturing screen.

Repeat the steps above and create these two screens. Remember to keep an eye out for our database field names that we defined earlier! If you get stuck, look at the end result below:

Create adduser.php in your backend folder.

Create your data capturing form.


<form method="post" action="<?php $_SERVER['PHP_SELF'];?>"/>

<input type="text" name="username" class="mytextbox" placeholder="Username" required/>

<input type="password" name="password" class="mytextbox" placeholder="Password" required />

<input type="email" name="email" class="mytextbox" placeholder="Email" required />

<input type="submit" value="Save Menu Item" name="saveuser" class="mybutton"/>

</form>


Add your PHP processing code, remember the security!

Add this above your <form> tag.

<?php

if(isset($_POST[‘saveuser])){

include('../includes/conn.php');

if ($letsconnect->connect_error) {

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

}else{

$menuname = $letsconnect -> real_escape_string($_POST[‘username']);

$item = $letsconnect -> real_escape_string($_POST[‘password']);

$itemlink = $letsconnect -> real_escape_string($_POST[‘email']);

$sql = "INSERT INTO menus(username,password,email) VALUES ('".$username."', '".$password."', '".$email."')";

if (mysqli_query($letsconnect, $sql)) {

echo "Your data was saved successfully!";

} else { echo "Error: " . $sql . "" . mysqli_error($letsconnect);

} $letsconnect->close();

}

}

?>


Please note that I will be covering Password security in the tutorials that follow.

Make sure that you are using your localhost server to complete this tutorial series. Do not publish your work until you complete this series.

Lastly, let's move to our content capturing screen which is currently found in index.php in the backend folder.

We will be changing this to a more professional dashboard in the tutorials that follow!
Our current file looks like this:


<html>

<head><title>Backend - Capture Content</title></head>

<body>

<?php

if(isset($_POST['savedata'])){

include('../includes/conn.php');

if ($letsconnect->connect_error) {

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

}else{

$title = $letsconnect -> real_escape_string($_POST['title']);

$content = $letsconnect -> real_escape_string($_POST['content']);

$author = $letsconnect -> real_escape_string($_POST['author']);

$sql = "INSERT INTO content (title,content,author) VALUES ('".$title."', '".$content."', '".$author."')";

if (mysqli_query($letsconnect, $sql)) {

echo "Your data was saved successfully!";

} else { echo "Error: " . $sql . "" . mysqli_error($letsconnect);

} $letsconnect->close();

}

}

?>

<form action="<?php $_SERVER[‘PHP_SELF'];?>" method="post">

<input type="text" name="title" placeholder="Content Title here" required/>

<textarea name="content">Content Here</textarea>

<input type="text" name="author" placeholder="Author" required/>

<input type="submit" value="Save My Data" name="savedata"/>

</form>

</body>

</html>


We need to modify this slightly to include our new field, content_type.

Add the input field in your <form> above the submit button.


<input type="text" name="content_type" placeholder="Content Type" required/>;


Next, add the content_type to the sanitization lineup.

$content_type = $letsconnect->real_escape_string($_POST['content_type']);


Lastly, store this variable to the database by modifying the $sql.

$sql = "INSERT INTO content (title,content,author,content_type) VALUES ('".$title."', '".$content."', '".$author."', '".$content_type."')";


Conclusion


Chopping and changing is not always as daunting. Find a rhythm. There are many ways to make cumbersome coding a breeze and we will delve into that in the tutorials to come.

Challenge


Think of ways to test what we just did through retrieving and echoing data from the database.

Next Up: #CodeWithMe Part 5 Building a good base Continued

SPONSORS

PHP Tutorials and Videos