How to use database query in codeigniter 4 - deesoft service

How to use database query in codeigniter 4

Deepak Tailor Image
Deepak Tailor - Oct 12 2020
How to use database query in codeigniter 4

The query() function returns a database result object when “read” type queries are run which you can use to show your results. When “write” type queries are run it simply returns TRUE or FALSE depending on success or failure. When retrieving data you will typically assign the query to your own variable, like this:

We pass any type of query to the query function of the codeigniter.

$db->query('YOUR QUERY HERE');

Simple query function does not return database value to us, these functions only return true or false. This function is used to check the query is successfully run or not.

$query_string = 'SELECT * FROM users';
$query = $this->seller->query($query_string);
if($this->seller->simpleQuery($query_string)){
	echo "query run";
	$result = $query->getResult();
	echo "<pre>";
	print_r($result);
}
else{
	echo "query fail";
}
How to use escape query in codeigniter 4

It is important to secure any value before saving it in the database. codeigniter 4 has given us 3 ways

1. escape ()

2. escapeString ()

3. escapeLikeString ()

How to use query binding

We use query binding to write a simple query.

Simple query binding with where condition

$sql = "SELECT * FROM users WHERE id = ? AND name = ?";
$query = $this->seller->query($sql, [3, 'deepak']);
echo "<pre>";
print_r($query->getResult());

use where in function in query binding

$sql = "SELECT * FROM users WHERE id IN ? OR name = ? ";
$query = $this->seller->query($sql, [[1,3],'arjun']);
echo "<pre>";
print_r($query->getResult());
how to use named binding

Instead of using the question mark to mark the location of the bound values, you can name the bindings, allowing the keys of the values passed in to match placeholders in the query:

public function namebind()
{
	$sql = "SELECT * FROM users WHERE name = :name: or name = :name:";
	$query = $this->seller->query($sql,[
		'name'	=>	'arjun',
		'name'	=>	'deepak'	
	]);
	print_r($query->getResult());
}
Deepak Tailor Image
Deepak Tailor

My name is Deepak tailor as a fullstack developer. I have been in the IT industry (PHP, Nodejs, flutter) for the last 5 years. For professional and customize web development & app development, you can send inquiry on our email.
----
You can contact him at deepaktailor10@yahoo.in