$99 Websites + Website Design 5505 Sun Harbor Road Panama City, Florida 32401 850-329-3425 http://website99.us https://www.google.com/maps/place/$99+Websites+%2B+Website+Design/@30.1842909,-85.7322502,15z/data=!4m5!3m4!1s0x0:0x61b35c1bb4fa6eac!8m2!3d30.1842909!4d-85.7322502
Friday, November 30, 2018
6 Books That Will Help You Become a Better Writer
What You Can Learn from MeToo Founder Tarana Burke
How to Master the Art of Conversation, According to One of the Best Conversationalists Ever
17 of the Most Inspiring Quotes on Leadership in History
13 Holiday Gifts That Will Make Any Entrepreneur Happy
Consider These 3 Things Before You Give Someone a Promotion (Or It Could Cost You)
The Follow-Up Question When Candidates Say, 'I'm A Team Player'
Boost Your Creative Content With These Podcasts
A Simple But Powerful Method For Getting More Writing Done (and Much Faster)
Are Millennials the New Entrepreneurs?
Here's How the World's Most In-Demand Freelancers Get Great Assignments--And Paid Top Dollar
Now That You're A Leader, Here's How to Improve This Essential Communication Skill
This Is What the Most Successful Teams Do Differently From Everyone Else
This Water Tech Entrepreneur Has Gained #1 Market Share by Breaking Conventional Marketing Rules
Have a Tendency to Procrastinate? Here's How to Fix It For Good
How to Become a LinkedIn Top Voice, According to LinkedIn's Editor-in-Chief
Black Friday Isn't a Holiday, But Here's Why Designated Shopping Days Matter
4 Big Reasons People Are Leaving San Francisco
Payless Shoes Becomes the Ultimate Troll in an Sneaky and Clever PR Move
More Female Founders Go From Raising Cash to Backing Other Startups As Angel Investors
How to Not Panic At The End of the Year
When Was the Last Time You Took 1 Hour In Your Work Day to Do Nothing? LinkedIn's CEO Does This Every Single Day
Looking to Make Your Employees Healthy and More Productive? It's Going to Take More Than Standing Desks
Up to 500 Million Customers' Data Stolen in Massive Marriott Security Breach
Here's How You Can Start a Business In 10 Minutes Per Day
Learning from Twitter, Facebook and Salesforce: How to Prevent the Pointed, Brave Employee Letter
This Simple Principle Will Dramatically Improve Your Communication
Can You Be an Effective Leader in an Open Office?
5 Tips for Reaching Your Goals in 2019
Is Your Corporate Culture Connected or Disconnected?
Working in a Crowded Market? Here's How to Stand Out and Improve Profit Margins
How Rich People Think Differently Than Everyone Else: This New Study Reveals the Personality Traits of Self-Made Millionaires
In 8 Words to His Kids, Jeff Bezos Explains What It Means to Be a Highly Successful Leader
Why People Don't Make Phone Calls Anymore, According to Psychology
The Reverse Performance Assessment is The Best Way to Get Feedback As a Leader
Why This Holiday's Most Brilliant Retail Promotion Will Fail
This Is the Best Time to Plan Your Big End-of-Year Meeting
This Is How Disney Became the Happiest Place on Earth (And How You Can Recreate That At Your Workplace)
Mock Donald Trump? That's What This Very Popular Airline Just Decided to Do (For Christmas, That Is)
Four Convincing Reasons Why Joining a Gym Should Be Part of Your New Year's Success Strategy
This Is the Best Time to Plan Your Big End-of-Year Meeting
This Is How Disney Became the Happiest Place on Earth (And How You Can Recreate That At Your Workplace)
Mock Donald Trump? That's What This Very Popular Airline Just Decided to Do (For Christmas, That Is)
Four Convincing Reasons Why Joining a Gym Should Be Part of Your New Year's Success Strategy
Here's the Highly Controversial Thing Facebook Announced on the Wednesday Before Thanksgiving (We Weren't Supposed to Notice or Remember, Right?)
Science Says the Most Successful Kids Have Parents Who do These 3 Things
New Study: What Men, Millennials, and Introverts Crave the Most in the Workplace
These Are The 5 Essential Personality Traits of a True Entrepreneur. Do You Have What It Takes?
Here's the Surprising Reason Very Rich People Are Driving for Uber (and Doing Other Gig Economy Jobs)
How Chick-fil-A Became an Iconic $9 Billion Business--Without Ever Going Public
Neuroscientists Discover How to Make an Open Plan Office Slightly Less Horrible
Thursday, November 29, 2018
2 Essential Qualities Every Good Leader Should Continuously Be Improving On
3 Things to Prepare Before Launching Your Retail Business
A 9-Year-Old Girl Wrote a Letter of Complaint to NBA Star Steph Curry. His Response Was Truly Brilliant
How to Attract Job Seekers to Your Company in Just a Few Seconds
Southwest Airlines Sassy Goes Too Far When a Gate Agent Mocks a Little Kid's Name
Want to Be a Better Negotiator? There's Only One Thing You Need to Know
3 Questions to Ask Yourself Before Pitching an Idea to Your Boss
6 Professional Places to Meet Clients Away From the Office
There is Danger and Evil Lurking in Short-Term, Cash Advance Loans
6 Clever Ways to Grow Your Email Newsletter Using Social Media
Why You Need to Start Networking Within Your Company--and How to Do It
7 Ways to Get Someone to Like You, According to an FBI Expert
Looking Past the Holidays: What Will Happen to Retail?
The Shocking Amount You Need To Earn To Be Upper Class (Do You Make the Cut?)
Elon Musk Wants You to Work 80 Hours a Week. Try This Smarter Strategy Instead
A Survey of 1,597 Marketers Revealed the 4 Steps Behind Every Successful Marketing Strategy
A Guide to the 7 Types of Business Travelers
Looking to Discover Your Passion? Try This Simple and Unconventional Approach
Here's How to Finally Travel The World and Work For Yourself
Why Researchers Say the Best Leaders Give the Worst Feedback
3 Digital Marketing Trends to Watch Out for in 2019
6 Free (Yet Invaluable) Holiday Gifts for Colleagues, Coworkers, and Friends
What a Self-Deprecating Sense of Humor Says About Your EQ
Why Your Cash Flow Problems Have Nothing To Do With Your Sales (And How To Fix It Quick)
Whole Foods Has to Pay $65K For Firing A Cashier With a Disability
These Are the 7 Steps I Use to Handle Any Major Company Crisis
3 Tweaks That Can Take Your Struggling Startup to Winning
How to Take the Conflict Out of Conflicting Advice
Want People to Like You? Clean Up Your Messy Office, Study Says
4 Tell Tale Signs That Things Need to Change In Your Company
The Campbell Soup Culture is About to Change Forever. And Their Story Will Teach You the Lesson of a Lifetime
Is it OK to Swear on Stage as a Speaker?
Warning: If You Work In One of These 2 Industries, You're Most Likely to be Targeted By Hackers
Holiday Deals Are Good, but Your Customers Want Experiences (Preferably Instagrammable Ones)
McDonald's Stunning New Coffee Sustainability Announcement Will Completely Change the Future of Fast Food
4 Simple Habits to Learn Like a Designer
This 1 Powerful Question Will Immediately Improve Your Emotional Intelligence
Starbucks Just Announced It's Going to Stop People Doing Something They Should Really Never Do (McDonald's Has Already Done It)
The Very Best GaryVee Quotes of 2018 to Inspire You to Go for Your Dreams
18 Simple Ways to Get More Done Today
Legendary Heavyweight Boxer Wladimir Klitschko Explains How to Maintain Greatness
Think You're a Great Manager? Make Sure You Haven't Forgotten These 4 Important Leadership Habits
How to Tell Stories That Eliminate Indifference for Your Brand: 3 Simple Lessons From Creed II
The 10 Best Business Books of 2018
Teach Your Child This 1 Thing If You Want to Raise an Entrepreneur
Scientists Just Found Something Absolutely Shocking on These McDonald's Self-Order Touchscreens
How This Five-Time Serial Entrepreneur Jumpstarts a New Company
These Entrepreneurs Teamed Up to Do Something That Hadn't Been Done for Decades: Make Flannel Shirts in the USA
Every Student, Teacher, Janitor and Bus Driver at This High School Just Got a $1,000 Cash Gift. Here's What Motivated the 89-Year-Old Donor
Elon Musk Is Wrong. You Can Definitely Change the World On 40 Hours a Week
The Real Power of Harnessing Empathy is in the Ability to Forgive
How Many Salespeople Are Hypocrites? A New Survey Cleverly Answers the Question
Wednesday, November 28, 2018
The 4 Most Common Lies People Tell on Dating Apps, According to a Stanford Researcher
Want Better Leaders on Your Team? Start Doing These 3 Essential Things
3 Reasons to Consider Small Towns for Entrepreneurship
You Should Avoid Unscheduled Phone Calls At All Costs. But If You Absolutely Must Call, At Least Consider This
Startup Found a Way to Do Good, Make Money, and Use Blockchain at the Same Time
Compensation Is More Than Just Salary. Here's How to Negotiate the Best Possible Offer
How You Dress at Work Is Way More Important Than You Think
Elon Musk Is No Longer Building a Tunnel Under the Westside of Los Angeles. He's Doing This Instead
What the Rise in Employee Activism in 2018 Means for the Future of the Workplace
5 Non-Spammy Ways to Gain Positive Customer Reviews Online
10 Inspirational Podcasts That Will Make You Better
7 Things in Leadership That Require No Talent But Lead to Massive Success
3 Proven Methods to Generate Excitement for Your Next Product Launch
Can Innovative Technology Fill Your Jewelry Box?
How to Make Your Toast the Star of the Holiday Party
Maintain Focus and Lower Stress By Starting Your Day With This
Quitting Your Job? Make Sure You Don't Make This Common Mistake Before Leaving
Why Now Might be the Best Time to Quit Your Job and Go on Your Own
Why Malcolm Gladwell Tells Entrepreneurs to Stop Only Focusing on 1 Thing
The Best Companies Make This 1 Mistake With Virtual Employees. Don't Let It Get You
This Is the Best Day of the Week to Take Off From Work
How to Conquer Meeting Fatigue and Reach Results Faster
4 Ways to Escape the Vortex of Meeting FOMO
How This Entrepreneur Turned a Podcast Into a Million Dollars in Funding for His Company (And How You Can Too)
Seth Godin Says You're Trying Too Hard to Sell
How Human Connection Contributes To Innovation
How Lack of Diversity Points to Facebook's Downfall
How Tom Condon Transformed the Role of NFL Player Agent (and Negotiated Some of the Biggest Deals in Football History)
9 Essential Questions to Ask Before You Take Out a Business Loan
Bird Is Offering Entrepreneurs Their Own Fleet of E-Scooters
The 20 Best Office Christmas Gifts for Coworkers
5 Artificial Intelligence Trends to Watch in 2019
3 Companies Putting Impact Ahead of Profits (and Enjoying More Success Because of It)
8 Ways Your Startup Can Overcome the Holiday Season Staffing Challenge
5 Ways to Motivate Yourself and Increase Your Productivity
Why Malcolm Gladwell Will Only Drink These 5 Liquids
How to Scale Your Business With Messenger Chatbots
Money Is Changing. Here Are the 3 Most Important Ways It'll Affect the Future of Your Wallet
Toronto Raptors Star Kawhi Leonard's Response to Greg Popovich Is a Lesson in Emotional Intelligence
4 Secrets Successful Entrepreneurs Wish They Could Tell Their Younger Selves
How to Recruit Generation Z According to a Human Capital Executive
How to Leave a Legacy of Significance
The Key to True Work-Life Balance Is Doing This 1 Thing
New Research Proves That You Should Really Only Focus on Your Own Work (and Not What Others Are Doing)
According to LinkedIn, These Are The Top 2 Challenges For Talent Development Professionals (Budget Is Not One of Them)
Women On the Verge Of Entrepreneurship: Why You Should and Can Take the Leap Today
The Surprising Thing This CEO Learned About Building a Team (After Firing a Top Performer)
This Morning Routine Is the Perfect Way to Start Your Day, According to Science
3 Things You Need to Stop Doing if You Want Others to Take You Seriously
Michelle Obama is Selling Out Arenas for Her Book Tour. The Important Lesson Every Brand Should Learn From It
It's Your Attitude Towards Your Work Not Your Hours That Impacts Your Kids' Happiness
Lyft Just Capped a Year of Milestones: 1 Billion Rides, $15 Billion Valuation, 80 Percent of the Bike-Share Market
The 7 Worst Marketing Fails of 2018
Turn Your Writing Into Professional Quality with These 5 Easy Tricks
Amazon Tells Its New Employees a Really Unusal Thing About Jeff Bezos. Here's the Explanation
The Secret No Customer Will Ever Reveal
Tuesday, November 27, 2018
Co-Founders Are Great. Co-CEOs Aren't. Here's Why
Will Your Relationship Last? Science Says Couples Who Do This 1 Thing Regularly are More Likely to Stay Together
How to Be a Compassionate Leader Without Being a Doormat
Elon Musk Says You Need to Work at Least 80 Hours a Week to Change the World
The 10 Most Significant Tech Acquisitions of 2018
This Is What It Takes to Successfully Manage Managers
5 Things We Learned From Amazon's Record-Breaking Cyber Monday Shopping Day
Science Shows This 1 Action Could Change Your Career Outlook Dramatically in 2019
6 Problems That Stop Your Startup From Growing, and How to Solve Them
Need New Ideas? Ask Your Staff These 7 Thought-Provoking Questions
How to Start an Online Store From Your Dorm Room or Home Office
What Happens When the Demand for Your Products Is So High That You Run Out of Inventory?
4 Best Strategies to Execute Now, to Get Ahead in the New Year
New York and D.C. Tech Companies: Here's How to Compete With Amazon
It's Official: Standing Desks Are the Most Overblown Health Fad of All Time
Meet the Women Changing the Financial Game for the Underserved and the Next Generation
Giant Companies Are Scooping Up Startups Before Their IPOs. What Silicon Valley Wishes Would Happen Instead
To End the Year Powerfully, Startups Should Do These 3 Things
Tips for Raising Capital From A Startup Operator and Former Venture Capitalist
Your Next Story Can Be As Simple As This
10 Signs You're a Mentally Strong Person (Even Though Most People Think These Are Weaknesses)
Want to Improve Teamwork at Your Company? Encourage Your Employees to Disagree With You
Forget the Cookie Basket. Here's What Entrepreneurs Really Want For Christmas
A Guide to Applying Entrepreneurial Thinking to Every Business Decision
Is Your Employee's Messy Desk Destroying Productivity? Here's an Emotionally Intelligent Fix
Don't Build Your Network; Nurture It
Some of the Craziest, Oddest, and Funniest Ads and Campaigns of 2018
What Businesses Can Learn From Theater Companies
When a Headhunter Makes His Profession Look Bad
6 Rare Things You Can Do to Make Your Life Better This Week (Why Don't More People Do This?)
Never Dread Mondays Again at This Workplace
Is There Any Way Through Mobile Phone Mayhem?
The 3 Main Types of Procrastinators, According to Psychology
Hate Meetings? It's Probably Because You're Unprepared
Why Good Management Doesn't Happen in the Middle of the Standard Distribution
The Worst Things You Can Do for Climate Change (It's Still Not Too Late to Make a Difference)
Steph Curry, the Best Player in the NBA, Needed These 5 Words to Overcome Self-Doubt
Why Investing in the Best Technology for Your Team Will Skyrocket Productivity
LinkedIn Surveyed 4,000 Professionals and Found a Critical Ingredient to Helping Employees Learn
11 Questions Interesting People Always Ask to Spark Up Great Conversations
Airlines Are Using This Dirty Trick to Make Themselves Look Better, A New Study Finds
How Carhartt Engineered Ageless Cool, and Won Fans From Skateboarders to Barack Obama
Facebook Launches Tool to Show How Much Time You Spend on Facebook. Here's Why You Should Use It
Here's How Stripe Plans to Help Entrepreneurs Around the World
The True Enemy of Success is Success
5 of Daymond John's Biggest Shark Tank Deals
A Woman Posted a Negative Yelp Review About a Bar. What Happened Next Shocked Her to the Core
Elon Musk Says: If You Want to Be Happy, Never Do This 1 Surprising Thing
A Passenger Asked For a Glass of Water On A Flight. What He Received Was Not the Sort of Water He Had In Mind
Monday, November 26, 2018
Are You Willing to Stretch the Truth While Negotiating?
Attention Passengers: Your Next Flight Will Likely Arrive Early. Here's Why
Is There Any Way Through Mobile Phone Mayhem?
From Work to Play, the Most Innovative Holiday Gifts of 2018
How Galia Lahav's CEO Got His Fairy Tale Ending
5 Gifts That Will Do Good Long After You Buy Them
Here is How You Can "Nail" Your Next Talk or Presentation By Using These 5 Strategies to Create A Powerful Presentation
Why Mark Cuban Made a $1 Million Deal For a Startup That Keeps Beer Cold
With an Unheard of Contract Clause, Taylor Swift Does Well by Helping Her Competitors
Climate Change Could Cut US GDP BY 10%. Here Are The Industries It's Hitting Hardest
Being Busy All the Time Is Probably Killing Your Productivity. Here's How to Fix It
These 5 Simple Lessons From the Movie Creed II Will Give You a Champion's Mindset
This is the Free Photo Editing App Top Influencers Are Obsessed With (and It's Finally Available for Brands)
Women Just Set a Record for Congressional Seats. Here's What it Teaches About Building Gender Diversity at Your Company
8 Smart Ways Your Business Can Use LinkedIn to Get Ahead
The Power of Simple Design: 3 Ways You're Losing Your Audience
Get Started With CRUD Operations in PHP MySQL Databases
In this article, we're going to explore how you could use a MySQL database to perform CRUD (create, read, update, and delete) operations with PHP. If you want to get your hands dirty with database connectivity in PHP, this article is a great starting point.
If you are just getting started with PHP, you probably realize that database connectivity is an essential feature that you'll need to get familiar with sooner or later. In most cases, a database is the backbone of any web application and holds the data of the application. So, as a PHP developer, you'll need to know how to deal with database operations.
In this article, we'll keep things simple and explore how to use the core mysqli functions. In upcoming articles of this series, we'll explore a couple of other ways to handle database connectivity.
Today, we'll go through the basics of database connectivity in PHP, and we'll use the MySQL database as our database back-end. Let's have a quick look at what we'll cover in this article:
- how to set up a database connection
- how to select a database
- how to insert and update records
- how to fetch records
- how to delete records
I assume that you've a working installation of PHP and MySQL, and that you're aware of the basics of MySQL. Also, you'll need to make sure that the mysqli extension is enabled in your PHP installation, since we'll use it to do database operations with the MySQL database.
If you are not sure about the mysqli extension, you can check it using the phpinfo()
function. In the phpinfo()
output, you can check if there's a section titled mysqli. You should also see the MysqlI Support | enabled header if the mysqli extension is enabled.
There's also an easy way to check it using the CLI interface. You can run the following command to list all extensions that are enabled with your PHP set up.
$php -m
It should print a list of extensions, and if it contains the mysqli keyword, the mysqli extension is enabled.
Now that we're set up, let's start creating a database connection.
How to Set Up a Database Connection
In this section, we'll discuss how you can establish a database connection using the mysqli extension.
There are two ways you can use the mysqli extension, procedural and object-oriented, but we'll use the procedural way in this post to keep things simple. If you're curious about the object-oriented syntax, let me know your questions in the comment section and I'll be happy to answer them.
Firstly, let's go through the syntax of the mysqli_connect
function which is used to set up a connection with the MySQL back-end.
<?php $connection_obj = mysqli_connect("{MYSQL_HOSTNAME}", "{MYSQL_USERNAME}", "{MYSQL_PASSWORD}", "{MYSQL_DATABASE}"); ?>
The mysqli_connect
function takes four arguments and returns the connection object upon successful connection. Let's go through the each argument:
MYSQL_HOSTNAME
: This should be replaced with the MySQL server's host-name or IP address. If you're working with the MySQL server in your local system, you can either uselocalhost
or127.0.0.1
.MYSQL_USERNAME
: The username of your MySQL user.MYSQL_PASSWORD
: The password of your MySQL user.MYSQL_DATABASE
: The database that you want to connect to.
Upon successful connection, the $connection_obj
contains the connection object. With this, you're ready to run queries against the database which was provided to the MYSQL_DATABASE
argument.
On the other hand, if the connection is not successful, we can debug it as shown in the following snippet:
<?php $connection_obj = mysqli_connect("{MYSQL_HOSTNAME}", "{MYSQL_USERNAME}", "{MYSQL_PASSWORD}", "{MYSQL_DATABASE}"); if (!$connection_obj) { echo "Error No: " . mysqli_connect_errno(); echo "Error Description: " . mysqli_connect_error(); exit; } ?>
In the next section, we'll see how you can select a specific database using the connection object.
How to Select a Database
In the previous section, we discussed how to set up a database connection using the mysqli_connect
function. In this section, we'll look at how to select a database once the MySQL connection is successful.
Of course, as we've already seen, you can always pass a database in the fourth argument of the mysqli_connect
function itself. But, there's also another way you could do this in case you want to change a database after you've connected to MySQL. You can use the mysqli_select_db
function to select a database to work with.
Let's revise the example discussed in the previous section to see how it can work.
<?php $connection_obj = mysqli_connect("{MYSQL_HOSTNAME}", "{MYSQL_USERNAME}", "{MYSQL_PASSWORD}"); if (!$connection_obj) { echo "Error No: " . mysqli_connect_errno(); echo "Error Description: " . mysqli_connect_error(); exit; } mysqli_select_db($connection_obj, "{MYSQL_DATABASE}"); ?>
As you can see, we've passed only three arguments in the mysqli_connect
function, and that should give us a successful database connection. Instead of passing a database in the fourth argument, we select the database using the mysqli_select_db
function.
The mysqli_select_db
function takes two arguments: the connection object and the database you want to connect to.
How to Create (Insert) and Update Records
In the previous sections, we discussed how to set up a MySQL connection and select a database to work with. Now, we'll look at how to execute different types of queries against the selected database. First, let's look at how to insert and update records.
If you want to follow along with examples discussed in this article, you'll need to create the following MySQL table in your database. It's the table which we're going to use in all the examples form now on.
CREATE TABLE `employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `phone` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Executing the above command in your MySQL database should create the employee
table.
How to Create Records
To keep things simple, we'll initialize values that need to be inserted into the employee table in the beginning of the script. However, in most of the cases, these would come from user input in the $_POST
variables submitted using a form.
<?php $connection_obj = mysqli_connect("{MYSQL_HOSTNAME}", "{MYSQL_USERNAME}", "{MYSQL_PASSWORD}", "{MYSQL_DATABASE}"); if (!$connection_obj) { echo "Error No: " . mysqli_connect_errno(); echo "Error Description: " . mysqli_connect_error(); exit; } // initialize variables for the insert query $name = 'John Smith'; $email = 'john.smith@yahoo.com'; $phone = '541-754-1234'; // prepare the insert query $query = "INSERT INTO employee(`name`,`email`, `phone`) VALUES ('". mysqli_real_escape_string($connection_obj, $name) ."','". mysqli_real_escape_string($connection_obj, $email) ."','". mysqli_real_escape_string($connection_obj, $phone) ."')"; // run the insert query mysqli_query($connection_obj, $query); // close the db connection mysqli_close($connection_obj); ?>
In the above script, we've first initialized variables that we’re going to use in the insert query. Next, we've prepared the insert query and assigned it into the $query
variable.
It's important to note that we've used the mysqli_real_escape_string
function to escape string values that we’re going to use in the insert query. You must use this function when you’re dealing with string values submitted via $_POST
variables. This ensures that your users don't inject malicious code into to your database queries.
Finally, we ran the insert query using the mysqli_query
function. The mysqli_query
function is used to run a query against the active database. To wrap things up, we used the mysqli_close
function to close the active connection.
How to Update Records
In the previous section, we discussed how you can insert new records in the MySQL table. In this section, we'll see how you can update a record which already exists in the table.
I assume that there's already a record exists in the employee table, and the id of that record is 1. In the following example, we're going to update a record which has a value of 1 in the id column.
<?php $connection_obj = mysqli_connect("{MYSQL_HOSTNAME}", "{MYSQL_USERNAME}", "{MYSQL_PASSWORD}", "{MYSQL_DATABASE}"); if (!$connection_obj) { echo "Error No: " . mysqli_connect_errno(); echo "Error Description: " . mysqli_connect_error(); exit; } // initialize variables for the insert query $id = 1; $phone = '333-555-4444'; // prepare the insert query $query = "UPDATE employee SET `phone` = '". mysqli_real_escape_string($connection_obj, $phone) ."' WHERE `id` = '". (int) $id ."'"; // run the insert query mysqli_query($connection_obj, $query); // close the db connection mysqli_close($connection_obj); ?>
As you can see in the above example, we want to update the phone
column of the employee
table where id
is 1. This is very similar to the insert query, except that we're using UPDATE
instead of INSERT
.
How to Retrieve Records
So far, we've discussed how to insert and update records in the MySQL table. In this section, we'll see how to retrieve (fetch) records from the MySQL table.
Take a look at the following example.
<?php $connection_obj = mysqli_connect("{MYSQL_HOSTNAME}", "{MYSQL_USERNAME}", "{MYSQL_PASSWORD}", "{MYSQL_DATABASE}"); if (!$connection_obj) { echo "Error No: " . mysqli_connect_errno(); echo "Error Description: " . mysqli_connect_error(); exit; } // prepare the select query $query = "SELECT * FROM employee"; // execute the select query $result = mysqli_query($connection_obj, $query) or die(mysqli_error($connection_obj)); // run the select query while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) { echo "ID:" . $row['id'] . "<br/>"; echo "Name:" . $row['name'] . "<br/>"; echo "Phone:" . $row['phone'] . "<br/>"; echo "Email:" . $row['email'] . "<br/>"; echo "<br/>"; } // close the db connection mysqli_close($connection_obj); ?>
The first thing that you need to do in order to fetch records from a database is to execute the select query using the mysqli_query
function. Upon successful execution of the select query, the mysqli_query
function returns the mysqli result
object, and that's what we've stored in the $result
variable above.
Next, we iterate over the result set using the mysqli_fetch_array
function in a while loop. The mysqli_fetch_array
function fetches a single row at a time from the mysqli result set.
The mysqli_fetch_array
function takes two arguments—the result object and result type. The result type indicates what type of array will be returned from the mysqli_fetch_array
function. It could be numeric, associative or both. It's an optional argument and you can pass one of these three values—MYSQLI_ASSOC
, MYSQLI_NUM
, or MYSQLI_BOTH
. MYSQLI_ASSOC
indicates that you want to access columns by their name, and MYSQLI_NUM
indicates that you want to access columns by their column number.
If you pass the MYSQLI_NUM
value in the second argument of the mysqli_fetch_array
function, you can access columns as $row[0]
, $row[1]
and so on. In our case, we've passed the MYSQLI_BOTH
value, so we can access columns in both ways. If you want to access only associative values, you can use the mysqli_fetch_assoc
function instead.
In the next and last section, we'll see how to delete records from a database.
How to Delete Records
In this section, we'll see how to delete records from a database.
Take a look at the following example.
<?php $connection_obj = mysqli_connect("{MYSQL_HOSTNAME}", "{MYSQL_USERNAME}", "{MYSQL_PASSWORD}", "{MYSQL_DATABASE}"); if (!$connection_obj) { echo "Error No: " . mysqli_connect_errno(); echo "Error Description: " . mysqli_connect_error(); exit; } // initialize variables for the delete query $id = 1; // prepare the insert query $query = "DELETE FROM employee WHERE `id` = '". (int) $id ."'"; // run the delete query mysqli_query($connection_obj, $query); // close the db connection mysqli_close($connection_obj); ?>
As you can see, it works pretty much the same as the insert and update queries. The mysqli_query
function executes the DELETE
query, and that eventually deletes the record from the employee
table.
Conclusion
In this article, we explored how you can use the MySQL database with PHP. This article was intended to provide you with a basic knowledge of MySQL database connectivity in PHP to beginners. We saw how to go from setting up a database connection to executing different types of queries.
Feel free to post your feedback and queries using the feed below.
Displaying the Date and Time in the WordPress Loop
Adding the date and time to the WordPress Loop seems like a simple enough task, right?
Well, yes. It can be a case of coding a simple template tag and letting WordPress do the work for you. But sometimes you can run into problems along the way.
In this quick tip, I'll show you the different functions WordPress gives you for displaying the date and time, and tell you which ones to use if you run into snags.
The Available Template Tags
WordPress gives you four functions to output the date and/or time. These are:
the_date().
By default it will echo the date of the post in the formatF j, Y
, so if the post was published on 20 November 2018, it would echo November 20, 2018.get_the_date()
- this fetches the date and doesn't echo it out. To echo it, you'd useecho get_the_date()
which gives you the same result asthe_date()
. It's useful if you're already usingecho
in your code. It can also help you get round the problem of dates not being displayed, as you'll see shortly.the_time()
andget_the_time()
- these fetch the time by default, but if you specify date formatting, you can also include the date. You could even this just to output the date if you configured the formatting to do so, but it would more sense to usethe_date()
orecho get_the_date()
.
Formatting the Date
Each function has a default format, which you can override if you need to. To do this, you'll need to use standard PHP date and time formatting.
Here are some examples, all for a post published on 20 November 2018.
the_date()
would output November 20, 2018 by default.echo get_the_date( l, S M Y )
would output Tuesday, 20th Nov 2018.the_time( 'g:i a' )
would output 2:03 pm.echo get_the_time( 'G:i' )
would output 14:03.the_time( 'g:i a, D, j F y' )
would output 2:03pm, Tues, 20 November 18.
Troubleshooting Dates in the Loop: Missing Dates in an Archive Page
If your'e using the_date()
to output dates on an archive page, and you find that the date isn't being displayed with some posts, that's because the_date()
doesn't repeat the date for subsequent posts published on the same day as a first.
Sometimes you might want to keep it like this, if you don't want to repeat the date for every post published that day.
But if you want to ensure that all posts have their date output with the title and any other content you're outputting, you'll need to use another function. You can use any of the other three functions above.
The simplest option is to replace the_date()
with echo get_the_date()
. If you wanted to add the time, either the_time()
or echo get_the_time()
will work.
Note: If you're puzzled by the fact that the_date()
throws up this problem, but the_time()
doesn't, it's because posts published on the same date weren't published at the same time. You'd have to go to a lot of effort, either scheduling posts, editing the publication times, or co-ordinating efforts between two bloggers, for that to happen!
I had this problem in the front page template of a theme I coded for a client. In this template were a number of loops, all leading to different content types on the site and all coded using WP_Query
. The problem wasn't apparent until the day they added two posts, (not something they normally did). They were puzzled as to why the second post's date didn't appear on the home page, and kept editing it, refreshing it and republishing it until they gave up and asked me.
Here's the original code:
<ul class="newsletters"> <?php $query = new WP_Query( array( 'post_type' => 'post', 'category_name' => 'newsletters', 'posts_per_page' => 8 ) ); while ($query->have_posts()) : $query->the_post(); ?> <li class="home newsletter"><a href="<?php the_permalink(); ?>"><?php the_title(); ?> - <?php the_date( 'j F' ); ?></a></li> <?php endwhile; ?> </ul>
I edited the one function so it read like this:
<ul class="newsletters"> <?php $query = new WP_Query( array( 'post_type' => 'post', 'category_name' => 'newsletters', 'posts_per_page' => 8 ) ); while ($query->have_posts()) : $query->the_post(); ?> <li class="home newsletter"><a href="<?php the_permalink(); ?>"><?php the_title(); ?> - <?php echo get_the_date( 'j F' ); ?></a></li> <?php endwhile; ?> </ul>
In the line beginning li class="home newsletter"
, I replaced the_date( 'j, F' )
with echo get_the_date( 'j, F' )
. It fixed the problem.
So if you ever find that dates aren't showing up in your archives, this might be the solution.
Black Friday Sees Spike in Online Shoppers
This Secretive Electric Car Startup Is Emerging From Stealth Mode With 600 Employees and Half a Billion in Funding
10 Refreshingly Original Products from 2018 That Do Something Brand New
VC Fred Wilson: My Amicus Brief
YouTube Tests "Ad Pods" at the Start of Videos to Increase Ad Views
How to Know If Your Business Is Ready for a Strategic Sale
The 1 Thing You Should Never, Ever Share With Your Employees
Your Answer to This 1 Question Is The Difference Between Thriving In An Unpredictable World Or Going Down In Flames
How to Make Sure You Don't Lead Your Team in the Wrong Direction
10 Ways to Make Working From Home More Productive (and Free Up More Time For Yourself)
When a Southwest Airlines Baggage Handler Started Throwing Around Boxes of Live Fish, This Passenger Had Enough
How Can You Be Sure Someone Has Emotional Intelligence? Watch for These 6 Signs
The No. 1 Reason People Won't Admit They Were Wrong
To Find Passion In Your Work You Need To Find This First
This Is the Book That Inspired Microsoft's Turnaround, According to CEO Satya Nadella
17 Inspiring Quotes That Will Make Your Heart Feel Full
Want to Give a Talk That Impacts the Audience? Follow the Counterintuitive 'Rule of Reversal'
3 Ways Owning a Dog Makes You a Better Leader
Salesforce Employees Objected to Its Immigration Work. CEO Marc Benioff's Response Was Brilliant
Before a Media Interview, Do What Pro Athletes Do: Train for It
4 Ways to Beat Amazon (and Other Big Box Retailers) This Holiday Season
This Software Company Has a $1 Billion Valuation, 700 Employees, and Zero Offices
After Many Years, Today is Apple's Day at the U.S. Supreme Court. The Stakes in This Case Could Not Be Higher
Sunday, November 25, 2018
On This Delta Flight, Smoke Appeared in the Cabin. What the Airline Did Next Stunned One Passenger
An American Airlines Flight Attendant Told the CEO: Our Standards 'Suck,' Compared to United and Delta. (His Reply Was Even More Shocking)
Use These 4 Simple Steps Every Day To Help You Create Work That Is Truly Original
I Just Stayed at One of Marriott's New Hotels For Millennials. I'm Still Recovering
American Airlines CEO Says Customer Service Isn't the Priority (Have a Guess What Is)
Apple CEO Tim Cook Just Revealed What He Does at 4 In the Morning. Here's Why More Business Leaders Should Do It
Want a Happy Marriage? This Is the Most Important Lesson You Need to Learn
Do the Holidays Hurt Your Mental Health? Try These Techniques to Minimize Stress
Saturday, November 24, 2018
An Open Letter to My Fellow Baby-Boomers
7 Awesome Cyber Monday 2018 Deals for Millennials and Young Adults
A Man Left His Wallet On a Plane. When He Got It Back, He Learned an Incredible Lesson in Making People Feel Good
The New Tax Law Puts a New Limit on Certain Losses. Don't Let It Trip You Up
Entrepreneurs Love to Talk About Goals, But These 3 Metrics Are Just as Important
Why a Supportive Boss Literally Determines Everything About Your Career Success
This Woman is Serving 10 Years in Prison for Lying to Get a Job
A Famous NPR Host Says These 4 Words Are the Best Icebreaker. Here's Why They're Not
Are You Worth Millions? Looks Like Your Family Will Get Another Big Tax Break. (But Everyone Else, Don't Read This)
United Airlines Flight Attendants Are So Angry They're Taking Drastic Action (Better Check Your Reservations)
This "Tribal" Leader Inspires His Tribe By Showing His Pain And Weaknesses
American Airlines Just Sneakily Scheduled Its Most Insanely Cramped Plane For a Really, Really Long Flight
A United Airlines Pilot Was Arrested. The Reason Why Is Truly Shocking, But How He Got There Is Even Crazier
Friday, November 23, 2018
A Driver Returned to His Car to Find a Note and An Incredible Lesson on Doing the Right Thing. The Note Was From a 6th Grader
George Orwell's Advice on How to Tweet Effectively
This Holiday Season, Let These Stirring Quotes Inspire You to Be A Shopper Warrior
How to Lead Your Creative Team With Trust
These Tiny Words on Your Website Are Hugely Important to Your Marketing Strategy. Here's Why
Coaching Your Team: Six Sports Books Every Business Owner Should Read
I Went to Walmart on Black Friday and Was Stunned By What I Saw
Why You Should Outsource These 4 Jobs
5 Ways to Recognize If Your Team Is Managed By Fear, and What You Can Do About It
This Baker Built a Loyal Community. It Saved Her Business When Cancer Struck
American Airlines Just Took a Massive Survey of 41,858 Employees. The Results Leaked, and They're Astonishing
4 Proven Ways to Improve Customer Service Using Social Media
A Scientific Analysis of 150 Different Studies Reveals Having a Few Good Friends Will Make You Live Longer
Feeling Down After the Holidays? Here's How to Perk Up
3 Key Habits for Maintaining Your Sanity, Energy, and Balance During the Holidays
Unlock the Remarkable Power of Aligning Your Brand and Your Culture
12 Remarkably Cool Gifts for Holiday Giving Guaranteed to Make a Really Big Impression
Want to Master The Art of Pitching? Check Out My 5 Ways to Perfect it
To Fix Facebook, Mark Zuckerberg Needs to Think More Like Jeff Bezos
This Fascinating New Ivy League Study Shows the 'Clear Causal Link' Between Facebook, Instagam and Snapchat and 'Loneliness and Depression'
Thursday, November 22, 2018
9 Killer Black Friday Deals for Millennials for 2018
Do These 3 Things Every Morning to Boost Your Productivity and Happiness
This Small Town Was Tired of Too Much Traffic. Its Sneaky Strategy to Change Things Was Annoying (And Quite Brilliant)
Always Be Prepared For Tough Financial Times
6 Things Every Entrepreneur Should Be Grateful for in 2019
Want to Go to Mars Someday? Scientists Say You'll Need These 6 Personality Traits
Bestselling Author AJ Jacobs Thanked a Thousand People Who Help Provide His Coffee. You Should Too
7 Brilliant Tricks Emotionally Intelligent People Use on Thanksgiving
17 Relaxing Quotes You Really Need When You're Feeling Stressed
Your Pumpkin Pie Probably Contains Zero Pumpkin. Here's What to Eat Instead
IKEA Just Announced Some Radical Changes That Will Change Everything You Think About IKEA (They Sure Hope So Anyway)
Wednesday, November 21, 2018
Have You Built a Culture of Creativity?
Why Every Parent Should Watch This Movie
This 1 Act of Gratitude Will Make Your Workplace Happier and More Productive
The Temptation of Online Loans Is Enticing. Here's Why You Should Beware
How to Book Last-Minute Business Trips Like a Pro
A Brilliant Email Marketing Strategy for Cyber Monday
How to Insure Your Home Against Wildfire Damage
Why Not Being Chosen for HQ2 Could Actually Open More Doors
3 Telltale Signs That It's Time to Change Jobs
The 3 Most Common Challenges Entrepreneurs Face--and How to Overcome Them
With Some Preparation, You Can Have a Conflict-Free Thanksgiving
After Thousands of Interviews, NPR's Terry Gross Has 6 Tips for Better Conversations
We Test A Thanksgiving Vegan Meal From Beyond Meat
Shark Tank Season 10 Review: Mark Cuban Left Speechless by Kombucha
Rolling in Dough: What Brands Can Learn from the Success of the Museum of Ice Cream
Can You Take That Huge 20% Deduction for Pass-Throughs? Use This Explainer as Your Guide
5 Ways to Show Your Employees That You're Thankful For Them
Audiences Crave Educational Content. Here Are 5 Ways to Give Them More
5 Common Traps Newly-Minted Managers Need to Avoid
10 Terrible Buzzwords You'll Hear in Silicon Valley Every Day
4 Email Marketing Tips to Drive Sales This Holiday Season
10 Powerful Ideas on Gratitude Every Leader Needs
Want to Motivate Your Team to Reach a Goal? Create a Winning Theme That Gives Purpose -- Here's How
4 Ways to Organize Your Workspace Before the New Year
The Green Bean Casserole Guide to Good Communication
How to Throw a Holiday Party Your Employees Will Actually Love
4 Minor Business Perks That Have a Major Impact on Employee Loyalty
Only 30 Percent of People Believe Their Teammates Are Committed to Quality Work -- Here Is How to Fix That
The 8 Best Business Documentaries of 2018
Conference Calls Are Terrible. This Startup Is Replacing Them With Holographic Meetings
Generate Random Alphanumeric Strings in PHP
Let me begin this post by saying that almost no event is truly random. Even the outcome of a classic coin toss could in theory be predicted if we knew the effect of every factor involved, like air friction, gravity, and initial force.
The same thing is applicable to the generation of random numbers and alphanumeric strings. The best we can hope for is to generate numbers and strings that don't seem to follow a pattern and can't be practically predicted by an attacker.
In this tutorial, we will cover different techniques for generating random numbers and alphanumeric strings in PHP. Some of them will be cryptographically secure, while others are meant only for casual use, like assigning pseudo-random file names or creating URLs and suggesting usernames.
Generating Random Numbers in PHP
There are three different functions for generating random numbers in PHP. All of them will accept a minimum and maximum possible value for the random numbers and output a random number for you. These are rand($min, $max)
, mt_rand($min, $max)
, and random_int($min, $max)
.
With rand()
, the minimum and maximum values of integers you can generate lie between 0
and the value returned by getrandmax()
. Before PHP 7.1.0, this function was about four times slower than mt_rand()
. However, starting from PHP 7.1.0, it has been made an alias of mt_rand()
. Unlike mt_rand()
, though, you can set the value of $max
to be lower than $min
without causing an error.
With mt_rand()
, the minimum and maximum values of integers you can generate lie between 0
and the value returned by mt_getrandmax()
. It relies on an implementation of the Mersenne Twister to generate random numbers. Watch out, though—prior to PHP 7.1.0, this function implemented an incorrect version of the algorithm to generate the numbers. However, it has been fixed in newer versions.
The function became even better in PHP 7.2.0 by getting rid of a modulo bias bug. This means that for some particular seeds, your sequence of random numbers will now be slightly better compared to older versions. Some specialized code might actually rely on this bias, though. If so, you can use the older seed algorithm by calling the mt_srand()
function to seed the random number generator and passing MT_RAND_PHP
as the value of the second parameter.
The mt_rand()
function has a period of 219937−1, which basically means that in best case scenarios you get as many as 219937−1 random numbers before the sequence starts repeating. You should note that repetition of a sequence is not the same as repetition of a particular number. In other words, you might get the same random number twice, but that does not mean that the sequence itself has started repeating. The following sequence is an example:
187 3276 1267 15 1267 34598 3467 125 17
In the above sequence, we had 1267 twice in the output, but that does not mean that the whole sequence started repeating after that. It's unlikely to get the same number repeated so soon in a random sequence, but it is possible!
Cryptographically Secure Random Integers
If you want cryptographically secure pseudo-random numbers, the random_int()
function in PHP is your best bet. It will generate random numbers between the provided $min
and $max
values, which default to PHP_INT_MIN
and PHP_INT_MAX
. Unfortunately, this function is only available starting from PHP 7.0. For versions before that, you can use this polyfill on GitHub.
Random Floats
Instead of generating random integers, you might also want to generate floats. This can be done effortlessly by simply dividing a random number with a value returned by mt_getrandmax()
. The following example will illustrate how to generate a random float between 0 and 1 or between any other minimum and maximum limits.
<?php // Output: 0.69458310943776 echo mt_rand(0, mt_getrandmax())/mt_getrandmax(); function mt_random_float($min, $max) { $float_part = mt_rand(0, mt_getrandmax())/mt_getrandmax(); $integer_part = mt_rand($min, $max - 1); return $integer_part + $float_part; } // Output: 10.199064863938 echo mt_random_float(10, 11); // Output: 35.540808309121 echo mt_random_float(15, 50); ?>
When generating a random float between given limits, we make sure that the random integer numbers do not go above $max - 1
. This way, we can be sure that adding the float part will not take the number above the maximum limit.
Seeding the Random Number Generators
One concept that needs a little bit of explanation is seeds. Put simply, these are just numbers that can be used to initialize the rand()
and mt_rand()
functions before generating any random numbers. The function which seeds rand()
is called srand($seed)
, and the function which seeds mt_rand()
is called mt_srand($seed, $mode)
.
It's important to remember that providing an initial seed value every single time before calling rand()
and mt_rand()
won't necessarily produce better random numbers. In fact, using the same seed each time will give you the same random number as well!
<?php mt_srand(10); // Output: 1656398468 echo mt_rand(); mt_srand(10); // Output: 1656398468 echo mt_rand(); mt_srand(10); // Output: 1656398468 echo mt_rand(); ?>
Seeding a random number is useful in situations where you want to generate a random but reproducible sequence. The following code snippet generates the same sequence of random numbers when run twice.
<?php mt_srand(10); $count = 0; while($count < 10) { echo mt_rand(0, 100)." "; $count++; } // Output on First Run: // 68 58 68 13 3 48 30 37 96 82 // Output on Second Run: // 68 58 68 13 3 48 30 37 96 82
Generating reproducible random sequences this way can help debug programs which were being tested using random data—if you keep track of the seed, you can reproduce the same input to figure out what went wrong.
Generating Random Alphanumeric Strings in PHP
There are many ways to generate random alphanumeric strings, and what you use will depend on your needs.
Generate Shuffled Strings
If you want to generate random alphanumeric strings from a fixed set of characters, you can use the str_shuffle($string)
function. This function will provide you a randomly shuffled string. Starting from PHP 7.1, the algorithm which determines the random order of characters in the output string has been changed to the Mersenne Twister.
Remember that the random string generated this way is not cryptographically secure. However, the string will still be pretty unpredictable for common use like generating random file names or URLs. Here are a few examples:
<?php $permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz'; // Output: 54esmdr0qf echo substr(str_shuffle($permitted_chars), 0, 10); $permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Output: video-g6swmAP8X5VG4jCi.mp4 echo 'video-'.substr(str_shuffle($permitted_chars), 0, 16).'.mp4'; ?>
Your output will most probably be different in both cases. In the first case, we just shuffled the permitted characters string and then took the first 10 characters of it. In the second case, we added "video" at the beginning of the generated string and ".mp4" at the end.
This method of generating random alphanumeric strings is very easy, but it has a couple of issues. For example, you will never get the same characters in your random string twice. Also, the length of the random output string can only be as long as the input string.
Generate Random Strings
If the problems I listed above are a deal breaker, you might want to look at some other implementations. The following code will solve both these problems.
<?php $permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; function generate_string($input, $strength = 16) { $input_length = strlen($input); $random_string = ''; for($i = 0; $i < $strength; $i++) { $random_character = $input[mt_rand(0, $input_length - 1)]; $random_string .= $random_character; } return $random_string; } // Output: iNCHNGzByPjhApvn7XBD echo generate_string($permitted_chars, 20); // Output: 70Fmr9mOlGID7OhtTbyj echo generate_string($permitted_chars, 20); // Output: Jp8iVNhZXhUdSlPi1sMNF7hOfmEWYl2UIMO9YqA4faJmS52iXdtlA3YyCfSlAbLYzjr0mzCWWQ7M8AgqDn2aumHoamsUtjZNhBfU echo generate_string($permitted_chars, 100); ?>
You can modify it to add particular suffixes and prefixes to the generated random string. People who are using PHP 7 can improve the string generation further by using the cryptographically secure function random_int()
instead of mt_rand()
.
Generate Random Hexadecimal Strings
If you want to generate random hexadecimal strings in PHP, you can also use either the md5($string, $raw_output)
or the sha1($string, $raw_output)
function. Both of them will generate hashes of a given input string.
You will keep getting unique hashes as long as the input is unique. This could be achieved by using the output of a function like time()
as the input. By default, md5()
will return a 32-character hexadecimal string, and sha1()
will return a 40-character hexadecimal string. These can be trimmed to a specific length using the substr()
function.
Here is an example of the output returned by these functions:
<?php // Output: 36e5e490f14b031e echo substr(md5(time()), 0, 16); // Output: aa88ef597c77a5b3 echo substr(sha1(time()), 0, 16); // Output: 447c13ce896b820f353bec47248675b3 echo md5(time()); // Output: 6c2cef9fe21832a232da7386e4775654b77c7797 echo sha1(time()); ?>
As you can see, generating random and unique hexadecimal strings up to 40 characters long is very easy in PHP.
Generate Cryptographically Secure Random Strings
The three functions to generate random alphanumeric strings that we have discussed so far are not cryptographically secure. Luckily, PHP also has a function called random_bytes($length)
to generate cryptographically secure pseudo-random bytes. The $length
parameter determines how long the output string should be.
Once you have the output in terms of random bytes, you can use the bin2hex()
function to convert them to hexadecimal values. This will double the length of the string.
<?php // Output: b7b33efa07915b60ad55 echo bin2hex(random_bytes(10)); // Output: a2e6cb1f25616324c8a11a2cceb0b47c590949ea echo bin2hex(random_bytes(20)); // Output: 25af3b86e11884ef5e8ef70a0ad06cba81b89ed6af3781a0 echo bin2hex(random_bytes(24)); ?>
Another function that you can use to generate cryptographically secure random bytes is openssl_random_pseudo_bytes($length, &$crypto_strong)
. The value of the second parameter can be used to determine if the output string will be generated using a cryptographically secure algorithm or not.
Final Thoughts
In this tutorial, we looked at the generation of random numbers and alphanumeric strings in PHP. Generating random numbers can be useful in a variety of situations, like in games where you have to spawn enemy players or randomly give users some clues about letters so they can form a whole word.
Just like random numbers, the generation of random alphanumeric strings can also be pretty helpful in many circumstances. With the help of str_shuffle()
, you can choose which set of characters appear in your random strings. With sha1()
and md5()
, you can easily generate random hexadecimal sequences, and with random_bytes()
you can generate cryptographically secure strings. This will allow you to generate meaningful yet randomized filenames and usernames that are hard to guess.
I hope you enjoyed this tutorial. If you have any questions, feel free to ask them in the comments.