Grab value of SELECT'ed value Codeigniter - php

$this->db->select('secretsalt,session_id');
$getSaltAndSessionIDFromDb = $this->db->get_where('Client', array('email' =>$ClientEmail)); // generated via registration
$result = $getSaltAndSessionIDFromDb->result_array();
$saltFromDb = $result[0]['secretsalt'];
$saltedPasswordToVerify = $ClientPassword.$saltFromDb; // combine inputted pass + salt from the db
$isValidUser = $this->db->get_where('Client',array('email'=>$ClientEmail,'pass'=>$saltedPasswordToVerify)); // compare inputted pass + salt vs db entry.
// If [1] row found, login
if($isValidUser->num_rows() == 1 ){
// set the "Logged in" vars:
$loggedInValue = 1;
$this->db->set('loggedIn',$loggedInValue); // Set valid row loggedIn value = 1.
// Validate using the below model (loginfunctionmodel) that there is:
// 1. valid session_id
// 2. loggedIn=1
$this->load->model('pages/loginfunctionmodel');
$this->loginfunctionmodel->check_if_loggedin();
}
else{
// nothing at the moment
}
I want to get the value of secretsalt and use it in the above code where {{HERE}} is listed. How do I do so?

if($getSaltAndSessionIDFromDb->num_rows() ==1)
$result = $getSaltAndSessionIDFromDb->result_array();
$salt = $result[0]['secretsalt'];
$saltedPasswordToVerify = $ClientPassword.$salt;
That should work

$rs = $this->db->select('secretsalt,session_id')->from('tablename')->get();
$result = $rs->result_object();
Then use the result.
$saltedPasswordToVerify = $ClientPassword.$result->secretsalt;
If I have understood your question, that should work.

Related

Hw can I get last inserted id in cakephp 3.x?

I am trying to get last inserted id in cake php 3.
if($this->request->is('post')){
$this->loadModel('MyPlaylists');
$playlistData = [];
$playlistData["user_id"] = $_POST['user_id'];
$playlistData["play_list_name"] = $_POST['play_list_name'];
$playlistData["section"] = $_POST['section'];
$playlistData["created"] = date('Y-m-d H:i:s', strtotime('now'));
$playlistData["status"] = 'active';
$playlist_en = $this->MyPlaylists->newEntity();
$this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$this->MyPlaylists->save($playlist_en);
$id=$this->MyPlaylists->id;
}
I have also tried:
$id=$this->MyPlaylists->lastInsertedId;
But it is giving error as below screenshot:
Your code needs some fine tuning.
$playlist_en = $this->MyPlaylists->newEntity();
$playlist_en = $this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$isValid = $this->MyPlaylists->save($playlist_en);
if ($isValid) {
$id = $playlist_en->id;
debug($id); // Check your last insert id
} else {
pr($playlist_en->errors()); // Check errors
}
Make a query selecting the first element of the query ordered in DESC. way
$newPlaylist = $this->Playlists->find('all',['order' => ['Playlists.id' => 'DESC']])->select(['id']);

How to generate unique username - PHP

I have strings of usernames in array . I want to generate a unique string of username which do not exits in array.(probably with some numbers following the username)
How do I achieve this?
I have summarize the code:
function generate_unique_username(){
$firstname = "james";//data coming from user
$lastname = "oduro";//data coming from user
$new_username = $firstname.$lastname;
$usersnames = array("james39","oduro32","kwame93","elvisasante","frimpong32","edward32","jamesoduro");
//Loop through ARRAY usernames and check elements against VAR $new_username
if (in_array($new_username, $usersnames)) {
//generate new username which is not inside array
//the new generated string should also be check against array to ensure is doens not exit.
}else{
return $new_username;
}
}
Thank you.
Generating username from the stored array is not a good practice, I would suggest you to use the database.
If you are using the database instead of the array, you can use the best method to generate the unique username as following:
function generate_unique_username(){
$firstname = "james";//data coming from user
$lastname = "oduro";//data coming from user
$new_username = $firstname.$lastname;
/* Note: writing here pseudo sql code, replace with the actual php mysql query syntax */
$query = "SELECT COUNT(id) as user_count FROM user WHERE username like '%".$new_username."%'";
$result = mysql_query($query);
$count = $result['user_count'];
if(!empty($count)) {
$new_username = $new_username . $count;
}
return $new_username;
}
I think in this case you should first off try and assign cooler user names to the users then when that fails you go for a number suffix. This is an approach I may use. You may need to change the code to your more preferred and secured mysqli call like using the PDO or MySQLI prepared statement.
//function that will be used to figure out if the user name is available or not
function isAvailable($userName){
global $mysqli;
$result = $mysqli->query("SELECT id FROM users WHERE user_name='$userName'") or die($mysqli->error());
// We know username exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
//echo 'User with this username already exists!';
return false;
}else{
return true;
}
}
function generate_unique_username($firstname, $lastname, $id){
$userNamesList = array();
$firstChar = str_split($firstname, 1)[0];
$firstTwoChar = str_split($firstname, 2)[0];
/**
* an array of numbers that may be used as suffix for the user names index 0 would be the year
* and index 1, 2 and 3 would be month, day and hour respectively.
*/
$numSufix = explode('-', date('Y-m-d-H'));
// create an array of nice possible user names from the first name and last name
array_push($userNamesList,
$firstname, //james
$lastname, // oduro
$firstname.$lastname, //jamesoduro
$firstname.'.'.$lastname, //james.oduro
$firstname.'-'.$lastname, //james-oduro
$firstChar.$lastname, //joduro
$firstTwoChar.$lastname, //jaoduro,
$firstname.$numSufix[0], //james2019
$firstname.$numSufix[1], //james12 i.e the month of reg
$firstname.$numSufix[2], //james28 i.e the day of reg
$firstname.$numSufix[3] //james13 i.e the hour of day of reg
);
$isAvailable = false; //initialize available with false
$index = 0;
$maxIndex = count($userNamesList) - 1;
// loop through all the userNameList and find the one that is available
do {
$availableUserName = $userNamesList[$index];
$isAvailable = isAvailable($availableUserName);
$limit = $index >= $maxIndex;
$index += 1;
if($limit){
break;
}
} while (!$isAvailable );
// if all of them is not available concatenate the first name with the user unique id from the database
// Since no two rows can have the same id. this will sure give a unique username
if(!$isAvailable){
return $firstname.$userId;
}
return $availableUserName;
}
//Get the unique user id from your database, for now let's go with 30
$userId = 30;
echo generate_unique_username('john', 'oduro', $userId);
Also, it would be nice to provide a fallback feature where the user can change their user name to any other unique value, in case they do not like the auto-generated value.

Converting 'String' value from MySQL table into Interger

I am writing some script in attempt to convert a "String" value, which is retrieved from a MySQL database table, into an INTEGER, which I will then use within my PHP code.
The PHP Select-statement:
Code:
$my_number = "SELECT my_number from numbers_table where login = '".$_SESSION['login']."'";
$result_my_number = mysqli_query($conn,$my_number);
$converted_number = ($result_my_number + 20); // add 20 to my_number
echo $converted_number;
This results in nothing...
I done some research and attempted this:
Code:
$converted_number = ((int)$result_my_number) + 20; // convert my_number into an INTEGER
Also did not get any thing from this, neither a error message.
So I thought I would extract everything from the table, into an array:
Code:
$my_number = "SELECT * from numbers_table where login = '".$_SESSION['login']."'";
$result_my_number = mysqli_query($conn,$my_number);
$row_my_number = mysqli_fetch_array($result_my_number);
if ($row_my_number) {
$actual_number = $row_my_number['my_number'];
}
$final_number = ($actual_number + 20);
echo $final_number;
And also did not get anything from this. Just a blank screen.
You need to use mysqli_fetch_row() to get the number from the database.
$my_number = "SELECT my_number from numbers_table where login = '".$_SESSION['login']."'";
$result = mysqli_query($conn,$my_number);
$row = mysqli_fetch_row($result);
$result_my_number = $row['my_number'];
$converted_number = ($result_my_number + 20); // add 20 to my_number
echo $converted_number;

PHP - Change value of variable before inserting into sql - Without Ajax

I have the variable
$sql1 .= "Brukertype";
Which gets information set from an already-filled textbox. It can either have the value Administrator or the value Iskjører.
What is the best way to change these values before inserting them into SQL?
The Administrator value should get changed to the value 1 and Iskjører gets changed to the value 2.
I can't use a select function (dropdown list) on the question because it needs to be enabled/disabled on my command.
This is a reasonable place to use a switch statement. You want a 'marshaling' function, like this:
function marshal_input($input) {
$result = 0;
switch ($input){
case 'Administrator':
$result = 1;
break;
case 'Iskjører':
$result = 2;
break;
case 'SomethingYouHaventThoughtOfYet':
$result = 3;
break;
default:
$result = 0;
break;
}
}
However, the implementation of the marshaling function can be almost anything:
function marshal_input($input) {
$options = array("Administrator" => 1, "Iskjører" =>2);
return $options[$input];
}
The point is that you need some code that maps from the human-readable form to the numerical representation the db needs. Then you just call it like so:
$sql_version = marshal_input($sql1);//Doesn't overwrite the variable
//...or...
$sql1 = marshal_input($sql1);//Note this overwrites the variable.
Since you have stated:
It can eighter have the value "Administrator" or the value "Iskjører"...
we only check whether the value is 'Administrator' or not.
Try this:
$val = 'Administrator'; // user input variable
$sql_val = ($val == 'Administrator') ? 1 : 2;
If value is 'Administrator' set $sql_val to 1, else set $sql_val to 2

PHP POST via AJAX loop through javascript sent object literal

Hey all i normally grab the ajax sent js object literal by doing this:
$_POST['called']
$_POST['chk1']
etc etc...
But now i have a problem that i cant seem to find a solution for.
Depending on how many checkboxes are selected, i loop (using js) to see all checked boxes and add them to the js object that ends up looking like this:
doBulk = {
called: "Approved",
chk0: "1789156857",
chk2: "5134465673753",
chk3: "234123554646",
chk10: "25511545542"
};
Now the chkXX can be any number from 0-19 (so 20 check boxes per page). I am sending that just fine to my PHP page but i am unsure on how to go about looping to get the needed data to update the database.
$chk1 = $_POST['chk0'];
$chk2 = $_POST['chk1'];
$chk3 = $_POST['chk2'];
$chk4 = $_POST['chk3'];
$chk5 = $_POST['chk4'];
$chk6 = $_POST['chk5'];
$chk7 = $_POST['chk6'];
$chk8 = $_POST['chk7'];
$chk9 = $_POST['chk8'];
$chk10 = $_POST['chk9'];
$chk11 = $_POST['chk10'];
$chk12 = $_POST['chk11'];
$chk13 = $_POST['chk12'];
$chk14 = $_POST['chk13'];
$chk15 = $_POST['chk14'];
$chk16 = $_POST['chk15'];
$chk17 = $_POST['chk16'];
$chk18 = $_POST['chk17'];
$chk19 = $_POST['chk18'];
$chk20 = $_POST['chk19'];
I could do a lot of if than else to check to see if each has data but there has got to be a better way of doing that?
So if i am doing a bulk mySQL update then i would have to run a query for each checkbox that i have a value for above? Is there also a better way of updating all the records that are needed in one swoop?
$result = mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID = " . $chk1 . "");
Thanks!
UPDATE
foreach($_POST as $key => $value)
{
// $key = CHK1-20
// $value = XXXXXXXXX
$dbBuilder = $value . ", " . $dbBuilder;
}
$dbBuilder = '(' . $dbBuilder . ')';
$result = mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID in $dbBuilder");
You can pass in the id's inside an IN SQL Clause. So, for instance you will have:
UPDATE userAccount SET Accept = 1 WHERE ID in $idCollection
Where $idCollection will be all of the IDs checked, separated by commas and inside parentheses, like so:
(1, 2, 3)
For the looping, you can iterate through the $_POST array as you would in any other array, and populate this string with the values read.
Hope that helps
for ($i=1;$i<=20;$i++){
${'chk'."$i"}=$_POST["chk"."$i"];
}
For UPDATE, i think you can use Mysql create procedure like this
$query=mysql_query("CREATE PROCEDURE dorepeat(p1 INT) SET $i = 0; REPEAT SET #i = #i + 1; UPDATE userAccount SET Accept = 1 WHERE ID = ${'chk'."$i"}; UNTIL #i =p1 END REPEAT; END") or (die mysql_error());
$result=mysql_query("CALL dorepeat(20)") or (die mysql_error());
EDIT: perhaps this is better without using CREATE PROCEDURE.
for ($i=1;$i<=20;$i++){
${'chk'."$i"}=$_POST["chk"."$i"];
$exp.=${'chk'."$i"}.',';
}
$exp=substr($exp,0,-1);
$exp='('.$exp.')';
$query=mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID IN '$exp') or (die mysql_error());

Categories