Codeigniter database update issues - php

I am having issues in updating a table in my database (MySQL workbench).
The code in my model is the following:
function updateMail($new) {
$data = array(
'email' => $new
);
$this->db->where('email', $this->session->userdata('email'));
$result = $this->db->update('person', $data);
$error = $this->db->error();
return $error;
}
My controller then places the return value in $result, and chechs if(!isset($result)).
the problem is that sometimes the table updates, sometimes it doesn't,
but the error is always set.
The table basically contains persons with an id, name, firstname, password, username, email, and patient field.
Am I doing something wrong? Or is there a way a can display the error message it throws?

Instead of error you have to check number of affected row in your query
function updateMail($new) {
$data = array(
'email' => $new
);
$this->db->where('email', $this->session->userdata('email'));
$result = $this->db->update('person', $data);
$afftectedRows = $this->db->affected_rows();
if ($afftectedRows > 0) {
return TRUE;
} else {
return FALSE;
}
}

Related

Pass parameter from URL to a php function in an api php

I have a working API written in PHP, my code works fine but I need to pass a parameters to the API. but it is not working as expected.
In my readOrders function, I am getting all the orders, but now I want to get all orders with ids above a particular number passed on from the url accessing the api.
function getOrders($last_oid){
$stmt = $this->con->prepare("SELECT oid, uid, order_num, create_date, status_date FROM orders WHERE oid > ?");
$stmt->execute($last_oid);
$stmt->bind_result($oid, $uid, $order_num, $create_date, $status_date);
$orders = array();
while($stmt->fetch()){
$order = array();
$order['oid'] = $oid;
$order['uid'] = $uid;
$order['order_num'] = $order_num;
$order['create_date'] = $create_date;
$order['status_date'] = $status_date;
array_push($orders, $order);
}
return $orders;
}
I was getting all the orders when I didn't have a parameter $last_oid. that parameter is to fetch orders with id WHERE id>? and pass the last_id in execute().
And in my API call, I am passing the last_id, it is currently hard coded, after I am done I will use $_GET to get the value and pass it to the function.
//the READ operation
//if the call is get orders
case 'getOrders':
$db = new DbOperation();
$response['error'] = false;
$response['message'] = 'Request orders successfully completed';
$response['orders'] = $db->getOrders(504);
break;
I am not sure what I am not doing right. I am getting an empty json but I could should be getting some few rows.
You have an error in the code. You are executing a "prepared statement" but with the wrong statements. Try it like this:
function getOrders($last_oid)
{
try {
$orders = array();
$stmt = $this->con->prepare("SELECT oid, uid, order_num, create_date, status_date FROM orders WHERE oid > ?");
// I assume $ last_oid is an integer.
$stmt->bind_param("i", $last_oid);
if ($stmt->execute()) {
$result = $stmt->get_result();
// use the while loop to load the result set
while ($row = $result->fetch_assoc()) {
array_push($orders, array(
'oid' => $row['oid'],
'uid' => $row['uid'],
'order_num' => $row['order_num'],
'create_date' => $row['create_date'],
'status_date' => $row['status_date']
));
}
return $orders;
}
} catch (Exception $ex) {
print $ex->getMessage();
}
}

How to prepare a PHP postgreSQL request with 'LIKE' keyword

i'm using Symfony4 and a postgreSQL database. i'm working on a search system. I would like to check if something match with the string i'm sending with ajax in my database. But the SQL query always returns false. How should i do to make this code works ? Thanks for help :)
public function search(Request $request) : Response {
if($ajaxRequest = $request->getContent())
{
$requestContent = json_decode($ajaxRequest, true);
$content = $requestContent["content"];
$connexionParams = "host=localhost port=5432 dbname=mydb user=myuser password=mypassword";
$db = pg_connect($connexionParams);
$sql = pg_prepare($db, 'search_query', "SELECT nom, lon, lat, id FROM site WHERE nom LIKE $1 OR id LIKE $2");
$result = pg_execute($db, 'search_query', array($content, $content));
var_dump($content, pg_fetch_row($result), $result);
$results = array();
while($row = pg_fetch_row($result)) {
$results[] = $row;
}
if(($results)) {
return new JsonResponse([
'result' => true,
'results' => json_encode($results),
]);
} else {
return new JsonResponse([
'result' => false,
]);
}
}
}
false means failure, not empty zero hits as stated here. Most likely there is an error in your SQL Syntax or connection data. Maybe pg_last_error helps to find the mistake:
if ($result === false) {
echo pg_last_error($db);
}

Function to block duplicate usernames in database when true, inserts names into database when true

I made this function to prevent duplicate usernames in my mysql database when registering. If it returns false then the name can be made:
public function nameTaken($username){
$statement = $this->pdo->prepare('SELECT count(*) FROM users WHERE name = :name');
$statement->execute(array('name' => $username));
$res = $statement->fetch(PDO::FETCH_NUM);
$exists = array_pop($res);
if ($exists > 0) {
echo 'user already exists';
return;
} else {
//the name can be made
return false;
}
}
When I tested it, even when it echo'd that users already exist and didn't return false, the username from the post request were still inserted into my database. Here is my function to insert into my database :
public function insert($table, $parameters){
$sql = sprintf(
'insert into %s (%s) values (%s)',
$table,
implode(', ', array_keys($parameters)),
':' . implode(', :', array_keys($parameters))
);
try {
$statement = $this->pdo->prepare($sql);
$statement->execute($parameters);
} catch (Exception $e) {
die('something went wrong');
}
}
and here is my controller that gets the post requests to to register a name
<?php
$hash = password_hash($_POST['password'], PASSWORD_BCRYPT);
if(!$app['database']->nameTaken($_POST['username'])){
$app['database']->insert('users', [
'name' => $_POST['username'],
'password' => $hash
]);
};
You need to return true when the username is taken, otherwise your if statement will match null and false:
if(!$app['database']->nameTaken($_POST['username'])){
return; is the same as return null; which is "falsy" (loosely equivalent to false).

How to check query result is null

Hi I want to check query result. If it's null I want to send data to DB. In my code even if result is null I can't update database.
$this->db->where('login',$data_db['login']);
$query = $this->db->get('users');
if(is_null($query)) // If Login doesn't exist in DB
{
$this->db->insert('users', $data_db); // Insert into DB
}
}
I was trying to do that in other way but If user doesn't exist I got "Trying to get non object etc"
Other way:
$this->db->where('login',$data_db['login']);
$query = $this->db->get('users');
$row = $query->row();
if($row->login)
{
$this->load->view('content/error');
}
else
{
$this->db->insert('users', $data_db);
}
I suggest read through user guide before you post a question again you may find what your looking for.
Try n $query->num_rows() userguide
public function somefunction($data_db = array()) {
$this->db->where('login',$data_db['login']);
$query = $this->db->get('users');
if($query->num_rows() > 0){
return TRUE;
} else {
$this->db->insert('users', $data_db);
}
}
could always just do this
if (mysql_num_rows($query)==0) {your code if its null}

CODEIGNITER call to a member function num rows on boolean

please i have an issue with codeigniter. when i try to log here is the result:
Fatal error: Call to a member function num_rows() on boolean in D:\xampp\htdocs\procurementSys\application\models\login_model.php on line 19
Below tho code of the relative file:
<?php
class Login_model extends CI_Model {
//this function checks whether the username and the password is in the database or not
public function check_login($username, $password){
$this->db->select('username, password, status');
$array = array('username' => $username, 'password' => sha1($password),'status' => 'active');
$this->db->where($array);
$query = $this->db->get('user');
if($query->num_rows() == 1) // if the affected number of rows is one
{
return true;
}
else
{
return false;
}
}
//this function returns the status of the user to be used in authentication
public function user_login_data($username, $password){
$this->db->select('status');
$array = array('username' => $username, 'password' => sha1($password));
$this->db->where($array);
$query = $this->db->get('user');
if($query->num_rows() == 1) // if the affected number of rows is one
{
$row = $query->row();
return $row->status;
}
// else
// {
// return false;
// }
}
public function user_role($username){ // this function gets the user's role from the database
$this->db->select('role');
$this->db->where('username', $username);
$query = $this->db->get('user');
$row = $query->row(0);
return $row->role;
}
public function department($username){ // this function gets the user's department from the database
$this->db->select('department');
$this->db->where('username', $username);
$query = $this->db->get('user');
$row = $query->row(0); // returns the first row with an array of objects that is stored in the row variable
return $row->department;
}
public function get_user_id($username){ // this function gets the user's department from the database
$this->db->select('userID');
$this->db->where('username', $username);
$query = $this->db->get('user');
$row = $query->row(0); // returns the first row with an array of objects that is stored in the row variable
return $row->userID ;
}
public function fullname($username){
$this->db->select('firstName, secondName');
$this->db->where('username', $username);
$query = $this->db->get('user');
$row = $query->row(0);
return $row;
// foreach($query->result() as $row) // returns the query as an array of objects
// {
// $data[] = $row; // equates the array of objects to an array variable
// }
//
// return $data;
// }
}
}
?>
I kept searching for a solution and found this post (Call to a member function num_rows() on boolean) . It gave me an idea but no real help. thanks
I got this error with MySQL Strict Mode enabled. When I disable Strict Mode, error disappeared.
To check this mode is already enabled
SHOW VARIABLES LIKE 'sql_mode';
To make it disabled
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
Something like this for the count:
$this->db->select('id');
$this->db->from('table');
$this->db->where($your_conditions);
$num_results = $this->db->count_all_results();
**Try something like this **
//this function checks whether the username and the password is in the database or not
public function check_login($username, $password){
$this->db->select('username, password, status');
$array = array('username' => $username, 'password' => sha1($password),'status' => 'active');
$this->db->where($array);
$query = $this->db->get('user');
$result = $query->result();
if($result->num_rows() == 1) // if the affected number of rows is one
{
return true;
}
else
{
return false;
}
}
CODEIGNITER send boolean as result if there is not result
for example as per your method
public function check_login($username, $password){
$this->db->select('username, password, status');
$array = array('username' => $username, 'password' => sha1($password),'status' => 'active');
$this->db->where($array);
$query = $this->db->get('user');
if($query->num_rows() == 1) // if the affected number of rows is one
{
return true;
}
else
{
return false;
}
If there is no data in table it send False while we are expecting some object on which we can work so before calling $query->num_rows() check if it is an object or not so code can be like :
$query = $this->db->get('user');
if(is_object($query)){
if($query->num_rows() == 1) // if the affected number of rows is one
{
return true;
}
}else{
return false;
}
You can write like that. It will work smoothly.
if($query !== FALSE && $query->num_rows() == 1) // if the affected number of rows is one
{
return true;
}
else
{
return false;
}

Categories