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";
}
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 ()
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());
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());
}
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