Calling PDO query within a function - php

I'm 'doomsday' (mysql_ depreciation!) prepping some of my older applications that take the use of mysql_ extentions. I am currently converting them into PDO.
I use a lot of functions to make my work easy. However I cant get the $db->query within a function to work. For example I'm converting this function:
function GetAccount($account_id){
$Query = mysql_query("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
if (mysql_num_rows($Query) > 0){
$Result = mysql_fetch_assoc($Query);
return $Result;
} else {
return false;
}
}
Into this PDO function.
function GetAccount($account_id){
global $db;
$Result = $db->query("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
if (count($Result) > 0){
return $Result;
} else {
return false;
}
}
I have established a PDO connection outside of this function, which works fine with queries outside of any function.
The problem for the second (PDO) function is that the $Result is empty. A var_dump returs: bool (false).
What am I forgetting/doing wrong?
Thank you :)

Fixed it, new function:
function GetAccount($account_id){
global $db;
$Result = $db->prepare("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
$Result->execute();
$Result = $Result->fetch();
if (count($Result) > 0){
return $Result;
} else {
return false;
}
}
The only thing I did was :
$Result->prepare("query stuff");
$Result->execute();
$Result = $Result->fetch();

Related

PHP duplicate check - isUnique()

function isUnique($email){
$query = "select * from registerform where email='$email'";
global $db;
$result = $db->query($query);
if($result->num_rows > 0){
return false;
}
else return true;
}
function isUnique($username){
$query = "select * from registerform where username='$username'";
global $db;
$result = $db->query($query);
if($result->num_rows > 0){
return false;
}
else return true;
}
error code: Cannot redeclare a function previously declared, how do I make it check the duplicate for email and username?
if I remove 1 of the code it is completely fine.
You could also make a generique function such as
function isUnique($field, $value)
{
$query = "select * from registerform where $field='$value'";
global $db;
$result = $db->query($query);
return $result->num_rows > 0
}
You should also check how to sanitize inputs => https://xkcd.com/327/
You have to rename the function name, e.g.: isUniqueEmail and isUniqueUsername
You cannot have two functions with the exact same name.

mysqli_fetch_assoc in object

how to do array in object or with arrow to right. sorry i'm still a junior
this is function and worked
function check_level($id) {
global $connect;
$query = "SELECT level FROM s_user WHERE id='$id'";
$result = $connect->query($query);
$level = mysqli_fetch_assoc($result) ['level'];
return $level;
}
I was try like this but error, idk how to array in object
function check_level($id) {
global $connect;
$query = "SELECT level FROM s_user WHERE id='$id'";
$result = $connect->query($query);
$level = $result->fetch_object(['level']);
return $level;
}
can you help me ? thanks.
You may have solved it already. But here's the function anyway, that checks if there is a result before returning a value.
This function returns NULL if no record retrieved.
function check_level($id) {
global $connect;
$level = NULL;
$stmt = $connect->prepare("SELECT level FROM s_user WHERE id= ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
if($result){
if($result->num_rows > 0){
$row = $result->fetch_object();
$level = $row->level; // this
}
}
else {
echo "MySQL Error: ".$connect->error;
}
return $level;
}
The function also uses prepared statement to prevent sql injection attacks.
Read more about sql injection. You have to prepare and bind the parameter as code above. The $stmt is only "statement" or variable.

Function giving correct answer in one case, not in any others

Below is the function I am using. It is strange because when I test the name "admin" it returns an associative array with all the correct columns and values, however every other name tests returns 0 as far as I can tell, meaning nothing is found from the query (I am entering the names perfectly as they are in the database).
I have a feeling this could be some sort of security feature of pdo or something but I don't understand why it is acting up this way.
I am using mysql.
Does anyone know the problem and how to resolve it? Thank you!
function getUserDetailsByName($name, $fields = "*")
{
$db = connect_db();
$query = "SELECT $fields FROM UserDetails WHERE userName=:username";
$result = $db->prepare($query);
$result->bindParam(":username", $name);
if (!($result->execute())) {
sendMessage (1,1,'Query failed',$query);
$db = null;
return;
}
if (!($result->fetch(PDO::FETCH_NUM) > 0)) {
$db = null;
return 0;
}else{
$result = $result->fetch();
$db = null;
return $result;
}
}
EDIT: Someone asked to post how I call the function.
$user = getUserDetailsByName($_POST['value']);
if($user == 0)
{
print "user = 0";
}
print_r($user);
function getUserDetailsByName($name, $fields = "*"){
$db = connect_db();
$query = "SELECT {$fields} FROM UserDetails WHERE userName = :username LIMIT 1;";
if(!$result = $db->prepare($query)){
return null;
}
$result->bindParam(":username", $name);
if(!$result->execute()) {
sendMessage (1,1,'Query failed',$query);
return null;
}
if(!$user = $result->fetch(PDO::FETCH_NUM)) {
return false;
}
return $user;
}
Why 2 fetches? Checkout and compare this to your code.
Use like this:
if($user = getUserDetailsByName($_POST['value'])){
// we have a user!
}else{
// we don't have a user!
}

MySQL query to PDO

I'm switching from MySQL to PDO and I'm unsure if this query is correct.. would I still be required to write the if command.
public function User_Login($_iUsername,$_iPassword) {
$username=mysql_real_escape_string($_iUsername);
$password=mysql_real_escape_string($password);
$md5_password=md5($_iPassword);
$query=mysql_query("SELECT _iD FROM users WHERE _iUsername='$_iUsername' and _iPassword='$md5_password' AND _iStatus='1'");
if( mysql_num_rows( $query ) == 1 ) {
$row = mysql_fetch_array( $query );
return $row['_iD'];
} else {
return false;
}
}
TO
public function User_Login($_iUsername,$_iPassword) {
$md5_password = md5($_iPassword);
$sth = $db->prepare("SELECT _iD FROM users WHERE _iUsername='$_iUsername' and _iPassword='$md5_password' AND _iStatus='1'");
$sth->execute();
$result = $sth->fetchAll();
}
First off, you're not properly parameterizing the query. It's great that you're using PDO, but one of the main purposes of the change is the ability to parameterize queries. Secondly, md5 is a very weak hash. I suggest using bcrypt instead. Finally, PDOStatement::rowCount is the method you are looking for.
$sth = $db->prepare("SELECT _ID FROM users WHERE _iUsername = ?
AND _iPassword = ? AND _iStatus = 1");
$sth->execute(array($_iUsername, $md5_password));
if ($sth->rowCount() == 1) {
$row = $sth->fetch(PDO::FETCH_ASSOC);
return $row['_iD'];
}
else {
return false;
}

unable to read value written in mysql database using php using a php function, just after the function is called

In a php function, i tried to insert a row in a database table as
function abnc()
{
$link = conn to db;
$query = "insert into table( a,c ,v) values (1,2,3);"
$result = mysqli_query($link, $query);
if(mysqli_rows_affected($link) == 1){
close conn;
return true;}
else{
return false;
close conn;
}
now, at other place, i called this function, and tried to read the values i had inserted
as
$done = abnc();
if($done)
{
$query = "select * from table where a=1 and c=2 and v=3";
$result = mysqli_query($link, $query);
echo "true";
echo mysqli_num_rows($result);
}
else
{
echo 'false';
}
the output i get is true0;
I think while the function was executing, the script just continued.
I want it to wait until function execution is finished.
Any solution ??
The script does not continue. When you call abnc() that function will be executed and return a value which you store in the variable $done. This value is presumably true since your output is true0.
In abnc() you insert a row. Which means that one row was affected and the function returns true. And you close the db connection, which might be why you cant access your inserted data later.
try this
$done = abnc();
$link = conn to db;
if ($done) {
$query = "select * from table where a=1 and c=2 and v=3";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
do {
$resultSet = array();
if (($row = mysqli_store_result($link))) {
while ($row = mysqli_fetch_assoc($row)) {
$resultSet[] = $row;
}
$return[] = $resultSet;
#mysqli_free_result($row);
}
} while (#mysqli_next_result($link));
return $return;
}
} else {
return false;
}
You closed the database connection in your function try opening it outside the function and closing at the end of your script.

Categories