how to upgrade designation in php data - php

i am working with a mlm company's site where i hv to design to upgrade the status of member from one step to higher after adding 5 members every member has to upgrade to upper level.i have some code but i dont know how to call this function
here is my code:-
function CheckAndUpgradeDesignation($username,$des)
{
if($des=='Crown')
return;
$q="SELECT introducer_id FROM members WHERE user_id='$username'";
$rs=mysql_query($q);
$r=mysql_fetch_array($rs);
$id=$r['introducer_id'];
$q="SELECT count(*) as total from members WHERE introducer_id='$id' AND designation='$des'";
$rs1=mysql_query($q);
$r1=mysql_fetch_array($rs1);
$t=$r1['total'];
if($t==5)
{
if($des=="VIP")
$des1="Journey";
else
if($des=="Journey")
$des1="Executive";
else
if($des=="Executive")
$des1="DreamFlight";
else
if($des=="DreamFlight")
$des1="Safari";
else
if($des=="Safari")
$des1="GoldRace";
else
if($des=="GoldRace")
$des1="RoyalRace";
else
if($des=="RoyalRace")
$des1="Aashiyana";
else
if($des=="Aashiyana")
$des1="Crown";
$q="UPDATE members SET designation='$des1' WHERE user_id='$id'";
mysql_query($q);
CheckAndUpgradeDesignation($id,$des1);
}
}
pls check anyone is this code looks right or need some change...............if u hv some question ask me

You would call the function like this: CheckAndUpgradeDesignation('1', 'GoldRace');
Also you might rename the function parameter $username to $userid, because the SQL uses user_id.
Please escape the values inserted into the SQL statment properly to avoid injections.
Maybe refactor the function into 3 functions:
fetchDesignation($user_id) - which returns the designation for a user_id
raiseDesignation($des) - which is the logic part to level up and returns the new level or false
updateDesignation($user_id, $des) - which inserts the new level into the db
This suggestions is a bit more flexible, but it depends on the use case.
It allows testing the logic for raiseDesignation() in a seperate unit-test, without touching the db. Also fetching the designation for a user_id is now seperate.

I could refactor your code separating some important tasks. In the other hand, I recommend you don't try to write large functions with lot of code, because it could be no easy to understand.
<?php
function CheckAndUpgradeDesignation($userId, $designation)
{
if ($designation == 'Crown') {
return;
}
$introducerId = GetIntroducerIdByUserId($userId);
$memberTotal = GetTotalOfMembersByIntroducerIdAndDesignationId($introducerId, $designation);
if ($memberTotal == 5) {
$designationValue = VerifyDesignation($designation);
UpdateDesignation($designationValue, $introducerId);
CheckAndUpgradeDesignation($introducerId, $designationValue);
}
}
function VerifyDesignation($designation)
{
$designationList = array(
'VIP' => 'Journey',
'Journey' => 'Executive',
'Executive' => 'DreamFlight',
'DreamFlight' => 'Safari',
'Safari' => 'GoldRace',
'GoldRace' => 'RoyalRace',
'RoyalRace' => 'Aashiyana',
'Aashiyana' => 'Crown'
);
if (key_exists($designation, $designationList)) {
return $designationList[$designation];
}
return null;
}
function GetIntroducerIdByUserId($id)
{
$query = "SELECT introducer_id FROM members WHERE user_id='$id'";
$result = mysql_query($query);
$response = mysql_fetch_array($result);
return $response['introducer_id'];
}
function GetTotalOfMembersByIntroducerIdAndDesignationId($introducerId, $designation)
{
$query = "SELECT count(*) as total from members WHERE introducer_id='$introducerId' AND designation = '$designation'";
$result = mysql_query($query);
$response = mysql_fetch_array($result);
return $response['total'];
}
function UpdateDesignation($designationValue, $introducerId)
{
$query = "UPDATE members SET designation='$designationValue' WHERE user_id = '$introducerId'";
mysql_query($query);
}
Also check VerifyDesignation function it could be more efficient instead use multiple if statements.
I hope it can help you.

Related

If Statement proper formula

I have looked on here about if statements. I have found a few things but I am having issues figuring out the proper statement formula.
I have 2 tables in the database with the following 2 fields
table 1
rct_app_id
table 2
uid
now if the uid field matches the rct_app_id field I want it to
echo "Green Light";
if they don't match
echo "No Go"
this is my formula
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql);
$rct_app_id = ['rct_app_id'];
if ($rct_app_id == 'uid') {
echo "Green Light";
} else {
echo "No Go";
}
?>
function query($query)
{
global $connection;
return mysqli_query($connection, $query);
}
Try this. but keep in mind its hard for people to figure out whats going on by bits and pieces and it makes it harder to help you.
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql);
while(($row = mysqli_fetch_assoc($result))!=false){
$rct_app_id = $row['rct_app_id'];
if ($rct_app_id == $user_id) {
echo "Green Light";
} else {
echo "No Go";
}
}
}
?>
You need to fix two lines. $result has the results from the database, so that's the source for the rct_app_id data. Then, when you do the comparison, you need to compare the two variables.
$rct_app_id = $result['rct_app_id'];
if ($rct_app_id == $user_id) {
The way you have it, you're comparing an array to a string.
When you do this:
$rct_app_id = ['rct_app_id'];
You're actually setting the variable $rct_app_id equal to an array with one element, although the syntax is incorrect. Instead, you need to get one element of the array that is returned from the database. This assumes that you have a function called query() that is working properly and returning an array.
Instead, we need to set the variable equal to one element of the array like so:
$rct_app_id = $result['rct_app_id'];
Then, when you do a comparison like this:
if ($rct_app_id == 'uid') {
you're saying if the variable $rct_app_id is equal to the string uid, which it's not. Variables always start with $ in php, strings are quoted. The variable set earlier in the script is $user_id (from SESSION), so we need to compare to that:
if ($rct_app_id == $user_id)
UPDATE: You've specified your sql lib, I've edited the answer below to work with your updated answer.
Since you didn't specify the library, I'm making the answer and the code edits with the assumption that you're using mysql. Though all queries and return functions use similar syntax, ie: mysql_fetch_assoc() = mysqli_fetch_assoc(), pg_fetch_assoc(postgres).
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql); //What type of query runs as just query()? mysql_query would go here if this was mysql. Some Libraries offer this as a function, but since you didn't specify the library, I'm going to change it to mysql_query and proceed as if you're using mysql.
//$rct_app_id = ['rct_app_id'];//This will never work.
//You need this:
while($row=mysqli_fetch_assoc($result)){
//We only expect one result
$rct_app_id=$row['rct_app_id'];
}
if ($rct_app_id == 'uid') {
echo "Green Light";
} else {
echo "No Go";
}
function query($query)
{
global $connection;
return mysqli_query($connection, $query);
}
?>

Use one or two php scripts for mysql

I have one script of php which should check if given user exists in Users table, and if not it creates it, if yes then it updates the existing user with new information.
Should I create all in one sql query to do the checks and insert/update or should I first use one php script to get row count and then use second script to insert/update new user?
I know SQL but only the basics, so it is not my strong side.
Also which solution is better towards client/server communication?
I really like to use this function:
function exists($detail, $table, $column, $value) {
$query = mysqli_query($this->connect, "SELECT `$detail` FROM `$table` WHERE `$column` = '$value'");
$count = mysqli_num_rows($query);
if($count >= 1) {
return true;
} else {
return false;
}
}
So if the user exists it will return true else false. After this check I would run another function / query to update a user.
the above function could look like this:
//SELECT `username` FROM `users` WHERE `username` = '$username'
if(exists('username', 'users', 'username', $username)) {
//run this code if true
} else {
//run this code if false
}

Check if multiple rows exist in MySQL using PHP

I am currently busy on a textbased RPG game, but I am stuck at one part right now.
In order to start a mission, the player does need some items, these are stored in a string: item:1x3-item:5x1 - (basicly item:IDxamount).I have already made a function that explodes the string into variables, but now the script needs to check if the player does have all the items listed.
I've tried to solve the issue with a foreach, but that returns positive or negative for every item, and I only need to know if the player has all items at once.
(don't mind the unsafe query)
$parseAmount is an array, containing all item ID's.
$uid is an variable containing userID
// check if player has all items
foreach($parseAmount as $itemID)
{
$check_query = mysql_query("SELECT * FROM `player_items` WHERE `player`='$uid' AND `item`=='$itemID' AND `value`>='$parseAmount[1]'");
if(mysql_num_rows($check_query)>=1)
{return true;}
else
{return false;}
}
If you want me to post the whole function, please let me know.
If I understood your question correctly you need something like:
foreach($parseAmount as $itemID) {
$sql = "SELECT COUNT(*) AS count
FROM player_items
WHERE player = '".mysql_real_escape_string($uid)."'
AND item = '".mysql_real_escape_string($itemID)."'
AND value >= ".intval($parseAmount[1]);
$row = mysql_fetch_array(mysql_query($sql));
if ($row['count'] == 0) {
return false;
}
}
return true;
You must not early return true. You know the result is true only after checking all the items. My code could be improved by selecting all the items at once, but it's up to you to build this.
Keep in mind my comment about the deprecation of the MySQL extension, using MySQLi and Prepared Statements it will look something like this (note that I never worked with MySQLi before and built it with help of the manual):
foreach($parseAmount as $itemID) {
$sql = "SELECT COUNT(*) AS count
FROM player_items
WHERE player = ?
AND item = ?
AND value >= ?"
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssi", $uid, $itemID, $parseAmount[1]);
$stmt->execute();
$row = $stmt->get_result()->fetch_array();
if ($row['count'] == 0) {
return false;
}
}
return true;

Is using mysql_num_rows (rowCount in PDO) necessary in update or insert query?

Should I be using mysql_num_rows (rowCount in PDO) in update or insert query?
Currently, my code looks likes this,
public function update_username(){
$q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id' LIMIT 1";
$r = $db->query($q);
if($r){
$message = "Updated successfully";
return $message;
}else{
return false;
}
}
Should I change it to like this?
public function update_username(){
$q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id' LIMIT 1";
$r = $db->query($q);
if($r){
$num = $r->rowCount();
if($num == 1){
$message = "Updated successfully";
return $message;
}else{
$message = "An error occurred";
return $message;
}
}else{
return false;
}
}
Normally, query goes through without any error, so I shouldn't worry about it too much, but which one would be a better coding practice? Or do you suggest something else?
Thanks so much in advance!
Actually the two codes do something different.
The first one will print "Update success" if the query was successfully executed. But a query can be successfully executed also without affecting any row, i.e. you have a WHERE statamenet that does not match. The second code will not print "Update success" if no rows were affected.
Of course, if you're sure that your WHERE statement has to match, you can use both codes without any difference and using the second one could help you to spot any potential bug, i.e. it doesn't match and so something went wrong (probably the id was different from the one you expected).
Generally, to answer your question, mysql_num_rows is needed only if you want to know how many lines were affected. It's not mandatory at all to use it.
So, it depends on what you want. Both are good, but they are different.
If you are 100% sure the variables are created by you and not someone else you can do it like that, but you can minimize the code more:
public function update_username(){
$q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id'";
if($db->query($q)){
return "Updated successfully";
}
return false;
}
First, because a query is executed successfully, doesn't necessarily mean that anything has been updated. So if you need to distinct the difference between a queries validity or the update change, then yes, rowCount would be a good practice.
Second, a prepared statement would be more wise to use when assigning variables (SQL injection, etc).
public function update_username(){
$q = "UPDATE usertable SET username = :user_name WHERE id = :user_id LIMIT 1";
$r = $db->prepare($q);
$r->bindValue(':user_name', $user_name);
$r->bindValue(':user_id', $user_id);
if($r->execute()){
$message = "Updated successfully: updated ".$r->rowCount();
return $message;
}else{
return false;
}
}
To avoid code duplication, maybe you should consider avoiding writing the same execution code for a query, and move that to a method/function which does that all for you, e.g
public function validateStmt($r) {
// validate query
if($r->execute()) {
// check result set
if($r->rowCount() > 0) {
return $r;
}
else {
// if a result set IS expected, then you might consider to handle this as
// a warning or an error
}
}
else {
// query invalid
}
}
Depending on the situation, you will have to choose which part you should use. mysql_num_rows() is used to check how many rows have been affected from your query you have executed. So, it's up to you to decide whether it is really necessary to add the mysql_num_rows() function in to your code or not.

Using a Drupal variable in SQL query

I'm trying to stuff a variable into a SQL query to return a value to a page.
$sql = 'SELECT account FROM users WHERE uid = arg(1)';
Where arg(1) = the user currently being viewed. I am outputting arg(1) at the top of the page, so I know it's there, but Drupal doesn't seem to want to take it. I've tried escaping several different ways. Below is the full code
function accountselect_getclientaccount() {
global $user;
$sql = 'SELECT account FROM users WHERE uid = arg(1)';
$result = db_result(db_query($sql));
return $result;
}
You could try:
$uid = arg(1);
$result = db_result(db_query("SELECT account FROM {users} WHERE uid = %d", $uid));
To avoid sql-injection, you should use placeholders (see db_query for more info):
$result = db_query("SELECT * FROM {users} WHERE uid = %d", arg(1));
Also note that db_result is meant for single-column, single-result queries. You probably want to use db_fetch_object. Additionally, there isn't a column in the users table called account.
function accountselect_getclientaccount() {
return (arg(0) == 'user') ? db_result(db_query('SELECT account FROM {users} WHERE uid = %d', arg(1))) : FALSE;
}
I don't know why you're using the global $user. Maybe you should be using $user->uid instead of arg(1)? This would save you checking arg(1) is actually a user ID.
This might be better:
function accountselect_getclientaccount($account) {
return db_result(db_query('SELECT account FROM {users} WHERE uid = %d', $account->uid));
}
Also: see the user hook. It might be best practice to return the 'account' col on the load operation (if you're not doing that already)
http://api.drupal.org/api/function/hook_user/6

Categories