PHP & MySQL useful snippets

For us, working with database in web development is a mandatory task. Here in this post I’m going to list, as much as I know, PHP & MySQL snippets that I frequently use.

In this post, I frequently mention $connection variable and I assume it contains database connection credentials, like username and password to access database.

Preventing SQL Injection

To protect our database, I must check what our users are inserting into db. I assign what users typed into a variable and I make it secure by calling this function:

$userinput = mysqli_real_escape_string($connection, $userinput);


I have a table called “users” and it contains usernames and passwords. If I want to select a user that his username is “habibie”, than I do this:

mysqli_query($connection, "SELECT * FROM users WHERE username= 'habibie' LIMIT 1");

I did limit it “1” because I only have one user with that username.

Check if there any user with that username

I need to check do I have a user with that username. So I do:

$sql = mysqli_query($connection, "SELECT * FROM users WHERE username= 'habibie' LIMIT 1");
if(mysqli_num_rows($sql) > 0){
	echo "I have.";
	echo "I don't have."

Leave a Reply

Your email address will not be published. Required fields are marked *