Use one or two php scripts for mysql - php

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
}

Related

how to upgrade designation in php data

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.

How to check if a specific value exists in table column

I have 2 tables in a database and they have a foreign key relation thru the column called id.
So I have the id (representing a user and is the primary key in the user table) from one table and want to check weather that user has existing data in the other table.
So I wish to run the id against the column called id in the other table and if the id exists in that column return value true.
I´m not getting any error at the moment but the method does not return any value. So I must be doing something wrong... Any help appreciated!
This is the class and method I have in one file:
class test {
public function dataExists ()
{
$db = Database::getInstance();
$classUser = new user();
$userId = $classUser->getUserData($_SESSION['id']);
$user = $userId['id'];
$query = $db->prepare("`id` SELECT * FROM `data`");
if ($user == $query)
{
return true;
} else {
return false;
}
}
}
And the in my view file I have this:
$classTest = new test();
$exists = $classTest->dataExists();
if ($exists == true) {
echo '';
}
Currently you are checking if a mysqli_stmt object (returned from prepare()) equals a number. How do you think this comparison should work?
You can do this via num_rows, this is taken pretty straight forward from the manual
public function dataExists () {
//...
if ($statement = $db->prepare("SELECT * FROM `data` WHERE `id`=?")) {
$statement->bind_param("i", $user);
$statement->execute();
//...
return ($statement->num_rows > 0);
}
}
Since you are working with classes, you might want to store the results of the query somewhere - asking for their existence implies that you might want to use them.
I shortened the return statement as
if ($a==$b) {
return true;
} else {
return false;
}
is equal to
return ($a==$b);
Why not just use the query statement
SELECT count(*) FROM `data` where `id` = ?
and then just test for the value returned.
This has the benefit of only returning the number of records that match your query rather than matching and returning all the records that do. While that may be okay for a small number of records if your second table has 50,000 records that match you probably don't want to pull all of them just to find out that there are 50,000 of them!

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.

PHP mySQL 404 function

The following function is designed to check whether this row in this tables exists. I know that it does not yet whether I $row or !$row the if function it does not do anything.
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
while($row = mysql_fetch_array($four_zero_four)) {
echo 'no'; die();
}
};
$name is the name field from the row and is working correctly in other functions.
Another way to check whether a row exists is by using the mysql_result function in conjunction with the COUNT function as such:
$query = mysql_query("SELECT COUNT(1) FROM `table` WHERE `field` = 'something'");
$result = mysql_result($query, 0);
When you now print out the $result variable, you will see the amount of rows that are actually being returned by the query. This is generally faster than using mysql_num_rows.
I'm not sure I understand the logic, aren't you printing "no"; die() when there IS a row found, instead of when now row is found? Either way, here's how I would check:
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
if (mysql_num_rows($four_zero_four) == 0) {
// ROW DOES NOT EXIST
} else {
// ROW EXISTS
}
};
Your code does not work because it wont even be executed if there is no row returned by your query.
Use mysql_num_rows() instead:
$count = mysql_num_rows($four_zero_four);
if($count <= 0){
die("no rows in this table!");
}
Also, you should maybe consider to use MYSQLi commands instead of the old mysql_query() implementation and SELECT *, as they are deprecated.

How do I make my own true / false return function?

I want to make my own function which performs in a similar manner to the following actual code.. ie
if(mysql_num_rows($res) == FALSE) {
// DO SOMETHING BECAUSE THERE ARE NO RESULTS
}
In my code, i'm repeating an SQL statement a few times around the place, and if there are results, then I go ahead and do stuff.
What I'd like to do is create my own FALSE return in my own function ie
if(my_special_function($variable) == FALSE) {
// DO STUFF
}
Is this as simple as in my special function having something like...
function my_special_function($variable) {
$sql = 'SELECT field FROM table WHERE something=$variable';
$res = mysql_query($sql);
if(mysql_num_rows($res) == FALSE) {
return FALSE;
} else {
return TRUE;
}
}
?
You can make your special function even simpler:
function my_special_function($variable)
{
$sql = "SELECT field FROM table WHERE something='{$variable}'";
$res = mysql_query($sql);
return mysql_num_rows($res) > 0;
}
Yes, that is all for a function. Why don't you try such things first before asking whether it works or not?
You should add additional error checking for mysql_query and replace $sql = 'SELECT field FROM table WHERE something=$variable'; by:
$sql = 'SELECT field FROM table WHERE something='.$variable;
I'd revise it a bit
function my_special_function($variable) {
$sql = "SELECT field FROM table WHERE something=$variable";
$res = mysql_query($sql);
if(mysql_num_rows($res)) {
return TRUE;
}
return FALSE;
}
Changes
No need for the else { ... } as if the if evaluation is true, it won't go any further, if it isn't, then FALSE is returned.
Changed the if statement to if(mysql_num_rows($res)) as mysql_num_rows() will return FALSE on failure, and a number on everything else. So, if there's 0 affected rows, or an error you won't get the return TRUE.
Inside your $sql variable you had single quotes, the literal $variable would be passed rather than what was passed to the function
I can see a few problems.
Variable interpolation does not happen in single quotes, also its advisable to not to substitute variable directly into queries.
$sql = 'SELECT field FROM table WHERE something=$variable';
should be
$sql = 'SELECT field FROM table WHERE something='.mysql_real_escape_string($variable);
mysql_num_rows returns false when there is a problem, say when its parameter is not a valid resource. If you really want to check the case of "no rows returned" you need to check its value for 0

Categories