mysqli_insert_id() expects exactly 1 parameter, 0 given in CodeIgniter - php

I have a problem, Please Help me. I'm using Code igniter
This is my code.
my Models (M_register.php)
class M_register extends CI_Model {
function __construct()
{
parent::__construct();
}
function add_account($data)
{
$this->load->database();
$this->db->insert('login',$data);
**return mysqli_insert_id();**
}
function changeActiveState($key)
{
$this->load->database();
$data = array(
'active' => 1
);
$this->db->where('md5(id)', $key);
$this->db->update('login', $data);
return true;
}
}
And this is partly code in Controller
$data = array(
'username' => $username,
'password' => $password,
'nama' => $nama,
'email' => $email,
'active' => 0
);
$this->load->model('m_register');
**$id = $this->m_register->add_account($data);**
$encrypted_id = md5($id);
enter code here
And this My error:

The error message is clear :
mysqli_insert_id() expects exactly 1 parameter, 0 given
You must give it the connection in parameter. For example :
$con = mysqli_connect("localhost","my_user","my_password","my_db");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)");
// Here the call to "mysqli_insert_id" takes the output of "mysqli_connect" as parameter
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
Source: https://www.w3schools.com/php/func_mysqli_insert_id.asp
I don't know in your code where you're doing the connection, but check that your call to $this->load->database() doesn't return the connection resource.

Pass the database connection variable as parameter
$query = $this->db->insert('login',$data);
return mysqli_insert_id($dbconnection);

You are using codeigniter, so it would be better if you use codeigniter functions only to perform database operation.
Definitely you will get result using mysqli_insert_id(db_connection_object)
But it would be better if you use inbuilt function of codeigniter
$this->db->insert_id();

Related

How i can fix preg_match() expects parameter error?

When i try login to site from Steam, i received error:
ErrorException in SteamController.php line 50:
preg_match() expects parameter 2 to be string, object given
For test i try to delete code from line 50, but nothing happened.
My login function in SteamController.php
public function login()
{
if ($this->steamAuth->validate()) {
$steamID = $this->steamAuth->getSteamId();
$user = User::where('steamid64', $steamID)->first();
if (!is_null($user)) {
$steamInfo = $this->steamAuth->getUserInfo();
$nick = $steamInfo->getNick();
if (preg_match("/Admin|admins|admin|/i", $nick)) {
$nick = 'ADmin';
}
\DB::table('users')->where('steamid64', $steamID)->update(['username' => $nick, 'avatar' => $steamInfo->getProfilePictureFull()]);
if ($user->partner == 0) {
\DB::table('users')->where('steamid64', $steamID)->update(['partner' => \Request::cookie('ref')]);
}
} else {
$steamInfo = $this->steamAuth->getUserInfo();
$nick = $steamInfo->getNick();
if (preg_match("/|Admin|admins|admin/i", $nick)) {
$nick = 'Admin';
}
$user = User::create([
'username' => $nick,
'avatar' => $steamInfo->getProfilePictureFull(),
'steamid' => $steamInfo->getSteamID(),
'steamid64' => $steamInfo->getSteamID64(),
'partner' => \Request::cookie('ref')
]);
}
Auth::login($user, true);
return redirect('/');
} else {
return $this->steamAuth->redirect();
}
}
What i need to do, for fix error?
Due to lack of information, I'm assuming that you're using invisnik/laravel-steam-auth package to handle Steam social login.
Being that case, $steamInfo is a instance of Invisnik\LaravelSteamAuth\SteamInfo which extends Illuminate\Support\Fluent.
So, I'm guessing $steamInfo->getNick() is an attempt to retrieve the private $this->attributes['nick'] property, if that's the case, then you're doing it the wrong way.
$steamInfo->getNick() // returns itself, an object. (Thats probably why you're getting "expects parameter 2 to be string, object given").
// The correct way:
$steamInfo->nick;
// or
$steamInfo->get('nick');
Hope it helps.

Passing a query to a module_hook that uses a second database

I would like to use another database connection that queries a database using a hook in my own module called 'connector'. This hook shall take a parameter that is a query which shall be executed using the secondary database before it switches back to the primary Drupal 7-database. The problem seems to be that the query is somehow generated for the (primary) Drupal database (as it's been created before switching to the secondary db), even though the SQL itself looks fine to me. What am I doing wrong here?
Hook:
function connector_api_db($query) {
$result = [];
$database_info = array(
'database' => variable_get('connector_db_name'),
'username' => variable_get('connector_db_user'),
'password' => variable_get('connector_db_pwd'),
'host' => variable_get('connector_db_host'),
'driver' => 'mysql',
);
Database::addConnectionInfo('secondary_db', 'default', $database_info);
db_set_active('secondary_db'); // Initialize the connection
/* This actually works but I can here not use my own query as a parameter in this function. Not what I want. */
//$query = db_select('registration')->fields('registration')
//->condition('id', 46, '=');
echo $query->__toString() . "<br />"; /* Get query string */
var_dump($query->getArguments()); /* Get the arguments passed to the string */
$result = $query->execute()->fetchAssoc();
echo "<pre>";
print_r($result);
echo "</pre>";
db_set_active(); // without the paramater means set back to the default for the site
drupal_set_message(t('The queries have been made.'));
return $result;
}
Invoking the hook:
$query = db_select('registration')
->fields('registration')
->condition('id', 46, '=');
$response = module_invoke('connector', 'api_db', $query);
This results into this:
SELECT registration.* FROM {registration} registration WHERE (id = :db_condition_placeholder_0)
array(1) { [":db_condition_placeholder_0"]=> int(46) }
Additional uncaught exception thrown while handling exception.
Original
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal.registration' doesn't exist: SELECT registration.* FROM {registration} registration WHERE (id = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 46 ) in connector_api_db() (line 70 of /<path-to-drupal>/drupal-7.61/modules/connector/connector.main.inc).
This is not an answer, strictly speaking, but rather a suggestion.
The thing is that your hook receives a $query already built with the original database connection, this explains the errors. To be effective, db_set_active() should be called before calling the Query constructor.
Otherwise, you would have to override constructors for both the Select class and its parent class Query, or more precisely "reconstruct" the Query builder instance for Select statements (and probably others too if you need range query etc.).
Also, unless having explicit requirements to provide a dedicated hook in this situation, it is not necessary.
For example it would be simpler to do something like this :
connector.module :
/**
* Implements hook_init()
*
* Adds secondary database connection information.
*/
function connector_init() {
$database_info = array(
'database' => variable_get('connector_db_name'),
'username' => variable_get('connector_db_user'),
'password' => variable_get('connector_db_pwd'),
'host' => variable_get('connector_db_host'),
'driver' => 'mysql',
);
Database::addConnectionInfo('secondary_db', 'default', $database_info);
}
/**
* Switches from primary to secondary database and the other way round.
*/
function connector_switch_db($db_key = 'secondary_db') {
return db_set_active($db_key);
}
Example :
// Set secondary db active.
$primary_db_key = connector_switch_db();
$query = db_select('registration')
->fields('registration')
->condition('id', 46, '=');
$result = $query->execute()->fetchAssoc();
// Switch back to the primary database.
connector_switch_db($primary_db_key);
This softer approach also prevents hardcode like (...)->execute()->fetchAssoc() and let the implementation free to execute and fetch the results as needed.
For future reference, this is what I came up with (caching bits included):
function connector_init() {
foreach([
'connector_db_host',
'connector_db_name',
'connector_db_user',
'connector_db_pwd',
] as $var) {
drupal_static($var, variable_get($var, ''));
}
Database::addConnectionInfo('secondary_db', 'default', [
'host' => drupal_static('connector_db_host'),
'database' => drupal_static('connector_db_name'),
'username' => drupal_static('connector_db_user'),
'password' => drupal_static('connector_db_pwd'),
'driver' => 'mysql',
]);
}
function connector_api_db($query) {
$result = [];
$sql_query = $query->__toString();
$arguments = $query->getArguments();
if (count($arguments) > 0) {
ksort($arguments);
}
$cache_id = 'sql_' . md5($sql_query . '|' . print_r($arguments, 1));
$cache = cache_get($cache_id, 'cache_connector');
if ($cache && $cache->expire >= time()) {
$result = $cache->data;
} else {
db_set_active('secondary_db'); // Switch to secondary db */
$query_failed = FALSE;
try {
$db_result = db_query($sql_query, $arguments);
$db_result = (0 === $db_result->rowCount()) ? [] : $db_result->fetchAssoc();
} catch (\PDOException $e) {
$db_result = [];
$query_failed = TRUE;
} finally {
db_set_active(); /* switch back to default */
}
$result = (object)[
'query' => $sql_query,
'arguments' => $arguments,
'result' => (object)$db_result
];
if (!$query_failed) {
cache_set($cache_id, $result, 'cache_connector', strtotime('+10 minutes'));
}
}
return $result;
}

where() showing "IS NULL" instead of variable value in codeigniter

$email='abc#abc.com';
$pass= 123;
$this->db->select('*')->from('user')->where('email',$email)->where('password',$pass)-> get()->result();
this gives result :-
'select * from user where email IS NULL and password IS NULL';
But it works with $this->db->query();
plz help me to find why its not taking like :-
'select * from user where email="abc#abc.com" and password="123" ';
Use this method. Hope it will help you
$email = "abc#example.com";
$password = "abc123";
public function getdata()
{
// first load your model if not added in your config/autoload file
return $this->db->get_where('table_name', array('email' => $email, 'password' => $password))->row_array();
}

how to update table using api in codeigniter

I'm stuck at updating table row using api in codeigniter,
i already have read tutorial from code tutsplus
but there's no spesific to do it,
so i tried by myself and got stuck :-(
url request:
http://localhost/work/bnilife/v1/signup/user/post?nopol=a1b2c3d4e5&username=agus&password=kucingtikus&captcha=c12ds
Here's the json respon:
{
"error": "error :-( "
}
My Controller look like this below:
public function user_post()
{
date_default_timezone_set('Asia/Jakarta');
$datestring ="%Y-%m-%d %H:%i:%s";
$time =time();
$datetime =mdate($datestring, $time);
$data = array (
'nopol' => $this->input->get_post('nopol'),
'username' => $this->input->get_post('username'),
'password' => sha1($this->input->get_post('password')),
'created_at' => $datetime,
'updated_at' => $datetime
);
$result = $this->signup_m->signup_insert($data);
if($result) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'error :-( '),400);
}
}
My model:
public function signup_insert($data) {
// Query to check whether username already exist or not
$condition = "nopol=" . "'" . $data['nopol'] . "'" ;
$this->db->where($condition);
$this->db->update('user', $data); }
Is there any something wrong or misstype,
thank you guys
i'm new at this stuff.
You can check codeigniter documentation how are working Database methods http://www.codeigniter.com/userguide3/database
public function signup_insert($data) {
$this->db->where('nopol',$data['nopol']);
return $this->db->update('user', $data);
}
In your case you need and return else you can't use the method as $result as it will be equal to NULL..
Check and CI Form Validation library as you don't validate your input data (even escaped) it may generate problems.
And importantly, you should write proper method names: signup_insert should INSERT not UPDATE.
'nopol' => $this->input->get_post('nopol') in this change to 'nopol' => $this->input->get_post('no_polis'),
also $this->db->where($condition) $condition is not defined.
Like #svetlio said,
i add some solution if nopol is typo(misstype) or null.
it will return false,
so i add some code to do it.
like this below:
if ($this->db->affected_rows() === 1) {
return true;
} else {
return false;
}
}
so it wont be like:
return $this->db->update('user', $data);

Searching a set of records in Zend Framework

I have written code to search for the First name and last name and display those particular records if available and perform actions like update and delete on those records , I have written the following code to search , please tell me what is the correct approach to build a search controller .I am getting the following error :
Message: Method "select" does not exist and was not trapped in __call()
The code I have written in the controller is :
public function searchAction($params)
{
$query = $this->select()
->from(
array('EMPLOYEES'),
array('FIRST_NAME','LAST_NAME','SALARY','HIREDATE')
);
$query = $this->_makeParams($query,$params);
return $this->fetchAll($query);
}
private function _makeParams($query, $params)
{
$firstname = isset($params['firstname']) ? trim($params['firstname']) : '';
$lastname = isset($params['lastname']) ? trim($params['lastname']) : '';
$salary = isset($params['salary']) ? trim($params['salary']) : '';
$hiredate= isset($params['hiredate']) ? trim($params['hiredate']) : '';
if($firstname!='')
{
$name = '%'.$this->quote($firstname).'%';//quote is my own function
$query->where("EMPLOYEES.FIRST_NAME LIKE '?'",$firstname);
}
if($lastname!='')
{
$query->where("EMPLOYEES.LAST_NAME =?",$lastname);
}
if($salary!='')
{
$query->where("EMPLOYEES.SALARY=?",$salary);
}
if($hiredate!='')
{
$query->where("EMPLOYEES.HIRE_DATE=?",$hiredate);
}
}
your error comes from the fact that your calling select() against the controller object instead of the database object:
public function searchAction($params)
{
//$this in this context is a Zend_Controller_Action object
//you need to query against your database object.
$db = Zend_Db_Table::getDefaultAdapter();
$query = $db->select()
->from(
array('EMPLOYEES'),
array('FIRST_NAME','LAST_NAME','SALARY','HIREDATE')
);
$query = $this->_makeParams($query,$params);
//again make sure to query against the database object
return $db->fetchAll($query);
}
if you don't have a database object created in your bootstrap.php or application.ini you can create one with the Zend_Db:
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => '127.0.0.1',
'username' => 'webuser',
'password' => 'xxxxxxxx',
'dbname' => 'test'
));
public function searchAction($params)
{
$db = Zend_Registry :: get('db');
$select = $db->select();
$query = $select->from(
array('EMPLOYEES'),
array('FIRST_NAME','LAST_NAME','SALARY','HIREDATE')
);
$query = $this->_makeParams($query,$params);
return $this->fetchAll($query);
}
You are getting the error because you have not created the object of Zend registry.So copy the function and replace your code

Categories