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}
Related
I have created a MYSQL Procedure to fetch employee details. The calling procedure is
function call_procedure($procedure)
{
require_once("database_connect.php");
$db = Database::getInstance();
$mysqli = $db->getConnection();
$result = $mysqli->query("CALL $procedure");
return $result;
}
I call this function from another page by using this function:
function get_emp_details($parameters){
//create the query
$procedure = "fetchEmpDetails($parameters)";
$result = call_procedure($procedure);
// check for empty result
if (mysqli_num_rows($result) > 0) {
// looping through all results
// products node
$response['DATA'] = sqltoarray($result);
// success
$response['RESULT'] = 0;
$response['MESSAGE'] = 'Employee Details found';
$response['REQUEST'] =1;
}
else {
$response['DATA'] = '';
// no products found
$response['RESULT'] = 1;
$response['MESSAGE'] = "Incorrect Employee ID";
$response['REQUEST'] =1;
}
// echo no users JSON
return $response;
}
When I am using both the functions in the same file it is working fine. However, when I am using the two functions in different files, I am not getting any results when calling get_emp_details function.
To debug, I tried to echo values of $procedure and $result. The string in $procedure is as expected, but the value I am receiving in $result is nothing.
The login() function which is also defined in the same file as the get_emp_details() function is working fine. It is the get_emp_details() that is causing the problem.
Can anyone help me with this?? Thanks in Advance...
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;
}
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;
}
}
I am getting very frustrated. I have two functions which have similar "instructions" ie: return values from a users table in the database.
The second one works fine, however the first one is returning an empty value.
Here is the code:
public function ValidateUser($username, $password)
{
$stmt = "SELECT password FROM users WHERE username = :username LIMIT 1";
if(!($grabUser = $this->db->prepare($stmt)))
{
return null;
}
$grabUser->bindParam(":username", $username, PDO::PARAM_STR);
$grabUser->execute();
$data = $grabUser->fetch();
if(count($grabUser->fetchColumn()) <= 0)
{
return null;
}
echo $data['password'].'s';
if(!password_verify($password,$data['password']))
{
return null;
}
return $this->core->encrypt($data['password']);
}
I'm trying to display the $data['password'] on the page just to test whether it returns a value from the database, however it is simply returning empty, whereas the query is returning a column because it passes the
if(count($grabUser->fetchColumn()) <= 0)
{
return null;
}
condition.
The $username and $password variables are both set, so they are no problem.
Just in case you ask, this is the function that does work properly:
public function ValidateFacebookUser($email, $fid)
{
$stmt = "SELECT username, password FROM users WHERE email_address = :email AND connected_fb = '1' AND connected_fb_id = :fb LIMIT 1";
if(!($grabUser = $this->db->prepare($stmt)))
{
return null;
}
$grabUser->bindParam(":email", $email, PDO::PARAM_STR);
$grabUser->bindParam(":fb", $fid, PDO::PARAM_INT);
$grabUser->execute();
$data = $grabUser->fetch();
if(count($grabUser->fetchColumn()) <= 0)
{
return null;
}
return array($data['username'], $this->core->encrypt($data['password']));
}
It does turn the username and password for that case. Why does it not work in the first function?
Thanks.
No, you shouldn't mix up ->fetchColumn and ->fetch and with LIMIT 1.
What happens is that you already ->fetch() the first row. After that invocation of ->fetchColumn(), there's no more row to fetch.
public function ValidateUser($username, $password)
{
$stmt = "SELECT password FROM users WHERE username = :username LIMIT 1";
if(!($grabUser = $this->db->prepare($stmt))) {
return null;
}
$grabUser->bindParam(":username", $username, PDO::PARAM_STR);
$grabUser->execute();
$data = $grabUser->fetch(); // fetch once
// no need to add ->fetchColumn checking
$ret = null;
if(!empty($data['password']) && password_verify($password,$data['password'])) {
$ret = $this->core->encrypt($data['password']);
}
return $ret;
}
Look at the manual for fetchColumn(). You can see that this fetches the next result set. So if you've already called fetch(), there should be no next result set as per your code:
$data = $grabUser->fetch();
if(count($grabUser->fetchColumn()) <= 0)
{
return null;
}
This will always return null with a LIMIT 1 or single row result.
I'm newbie in PHP and WordPress. This approach was working fine for me in ASP.NET but here both queries are not working. When I comment the first one, the second one(Insertion) is working fine.
$dbhostname="111.1.11.111";
$dbusername="db_userName";
$dbpassword="mypassword";
$con=mysqli_connect($dbhostname,$dbusername,$dbpassword,"db_name");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Check wether the email exists or not ?
$sql="CALL Select_ConfirmEmailExistance('abc#abc.com')";
$containsResult=0;
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_assoc($result))
{
if (isset($fieldinfo)) {
$containsResult=1;// Email Exists
}
}
mysqli_free_result($result);
if ($containsResult==0) { // In case email does not exists enter it.
$sql="CALL insert_Userinfo('abc','def','abc#abc.com','mnop')";
if ($result=mysqli_query($con,$sql))
{
$data;
while ($fieldinfo=mysqli_fetch_assoc($result))
{
$data[]=$fieldinfo;
}
}
}
print_r($data);
}
mysqli_close($con);
First Store Procdure
BEGIN
SELECT 1 as emailstatus FROM userinfo WHERE email= p_email;
END
Second Stored Procedure
INSERT INTO `userinfo` (
`first_name`,
`last_name`,
`email`,
`password`
)
VALUES
(
`FName`,
`LName`,
`Email`,
`Pass`
);
SELECT
user_id
FROM
userinfo
ORDER BY
user_id DESC
LIMIT 1;
Here is what I was talking about when I said create a query class to fetch data. This is just a simple one, but it works pretty effectively and you can build it out to be pretty powerful.
class DBEngine
{
public $con;
public function __construct($host="111.1.11.111",$db = "dbname",$user="db_userName",$pass="mypassword")
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
while($rows = $query->fetch(PDO::FETCH_ASSOC)) {
$array[] = $rows;
}
}
return (isset($array) && $array !== 0 && !empty($array))? $array: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
// Create an instance of the engine
$query = new DBEngine();
// Query 1 will return an array or false (0)
$call1 = $query->Fetch("CALL Select_ConfirmEmailExistance('abc#abc.com')");
// Assign your true/false
$containsResult = ($call1 !== 0)? 1:0;
// Run second query and return array or false (0)
if($containsResult == 0)
$data = $query->Fetch("CALL insert_Userinfo('abc','def','abc#abc.com','mnop')");
// Display returned result
print_r($data);
It is quite simple. Your code is fine but you only have to create two separete functions and simply call those functions instead of the code directly.