SQL Operations

Working with Strings

For security reasons, when querying the database using string data of any type, it is highly recommended that we escape special characters in a string by using function mysqli_real_escape_string(). You pass to this function the $con (connection variable) and $string (string variable) as parameters. Here is an example:

//Make connection
$conn = mysqli_connect("mysql or localhost", "username", "password", "database");

//Check connection
if (!$conn){
die("Failed to connect to the database".mysqli_connect_error());
}

//Escape variables for security
$firstName = mysqli_real_escape_string($conn, $_POST["firstName"]);

$lastName = mysqli_real_escape_string($conn, $_POST["lastName"]);

$age = mysqli_real_escape_string($conn, $_POST["age"]);

//Construct the SQL statement
$sql = "

insert into persons (
firstname,
lastname,
age

) values (
'$firstName',
'$lastName',
'$age'
);

";

//Execute the SQL
if (!mysqli_query($conn, $sql)){

echo("Error encounterd:
".mysqli_error($conn));

$errorEncountered = true;

} else {

echo "
1 record added

";

}

//Close connection
mysqli_close($conn);




Pattern (wildcard) searches

You can use the operand LIKE and the wildcard % to carry out pattern searches in database tables. For e.g.

select * from persons
where firstname like 'p%'
and lastname = 'crowley';

Error encountered connecting to the databaseAccess denied for user 'pthakran'@'localhost' (using password: YES)