Nested function inside While loop - PHP [duplicate] - php

This question already has answers here:
Running a loop that has a function inside it
(9 answers)
Closed 2 years ago.
I have the below code that I am trying to fix. In this code, I have created a class and that has a function testcal() in it. In that function, I connect to database, do a select query from a table. For the result set, I want to loop through and grab values of fields $field1,2,3. Using those fields I am creating another function to throw out the result.
<?php
class test
{
public function testcal()
{
set_error_handler(function($errno, $errstr){
error_reporting(0);
}, E_WARNING);
//database credentials
$host = "localhost";
$db_name = "mydb";
$username = "root";
$password = "";
//connect to database
$con = mysqli_connect($host,$username,$password,$db_name);
//Query to generate check-in variables from ffc_contrast
$sql = "SELECT * FROM mytable";
//Store result on $result variable
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result))
{
//assign values to each variable
$field1 = $row["field1"];
$field2 = $row["field2"];
$field3 = 0.5;
////////////////
//Calculations//
////////////////
function ratingcheck($field1,$field2){
if($field1 == 0 || $field2 == 0){
return 0;
} elseif ($field1 == 1) {
return 1;
} elseif ($field2 == 2) {
return 2;
}else{
return null;
}
}
}
}
}
$test = new test();
print $test->testcal();
?>
I am getting an error saying Cannot redeclare ratingcheck() (previously declared in ~/myfile.php:51) in ~/myfile.php on line 37 I have declared the method correctly and have called the parent method. Not sure why I am getting this error. Can someone help?

class test
{
public function testcal()
{
....all your code....
//Store result on $result variable
$result = mysqli_query($con, $sql);
$returnValues = [];//not sure what you want here really, as you're returning inside youe while loop
//so that will only do 1 iteration anyway, so i'm assuming you want to build an array or something
while($row = mysqli_fetch_assoc($result))
{
//assign values to each variable
$field1 = $row["field1"];
$field2 = $row["field2"];
$field3 = 0.5;
//store the result from the function
$returnValues[] = $this->ratingcheck($field1,$field2);
}
return $returnValues;
}
////////////////
//Calculations//
////////////////
//declare the function once as part of the class, now you can call it
//i've put private here as it's making an inernal calculation, make it public if you prefer
private function ratingcheck($field1,$field2){
if($field1 == 0 || $field2 == 0){
return 0;
} elseif ($field1 == 1) {
return 1;
} elseif ($field2 == 2) {
return 2;
}else{
return null;
}
}
}
$test = new test();
print $test->testcal();

You are recreating the function ratingcheck on every iteration of the while loop. You cannot redeclare functions.
You need to move the function outside the loop and then call it from inside the loop.

Related

Error in counting the rows from the database using php for pagination

I am trying to learn pagination using php and mysql. I have created a function to count the rows in the table to store it and use it in the pagination function but no result occurs and I am unable to understand the problem in the code.
function get_row_count() {
$connect = connect();
$sql = "SELECT COUNT(*) AS rows From class";
$d = mysqli_query($connect, $sql);
$c = mysqli_num_rows($d);
if ($c == true) {
$row = mysqli_fetch_assoc($result);
return $row['rows'];
} else {
echo "<script>alert('error')</script>";
}
}
}

How are variables inherited in PHP functions (globals/locals)?

My primary programming language is python, but I inherited a PHP project to maintain, and I am trying to fix some SQL injection vulnerabilities. I have one file that has me baffled. It is working, but I have no idea how. On line 14, it invokes $db, but I do not understand how $db is available within that function. It is defined in other php files within the project, but my understanding was that global variables have to be declared (as $tbl_users is) to be available inside a function. Where else do I need to look to know where authValidateUser is getting $db from?
<?php
$user_list_link = "edit_users.php";
function authValidateUser($user, $pass)
{
global $tbl_users;
$user = strtolower($user);
$pass = md5($pass);
$user = preg_replace("/[^a-z0-9.]+/i","",$user);
$pass = preg_replace("/[^a-z0-9.]+/i","",$pass);
return sql_query1($db, "select count(*) from $tbl_users where name = '$user' and password = '$pass';");
}
function authGetUserLevel($user, $lev1_admin)
{
// User not logged in, user level '0'
if(!isset($user))
return 0;
// Check if the user is can modify
for($i = 0; isset($lev1_admin[$i]); $i++)
{
if(strcasecmp($user, $lev1_admin[$i]) == 0)
return 2;
}
// Everybody else is access level '1'
return 1;
}
?>
sql_query1 is the following:
function sql_query1 ($db, $sql)
{
$r = mysqli_query($db, $sql);
if (! $r) return -1;
if (mysqli_num_rows($r) != 1 || mysqli_num_fields($r) != 1
|| ($result = mysqli_result($r, 0, 0)) == "") $result = -1;
mysqli_free_result($r);
return $result;
}

Output multiple values from PHP function

I have created the following function to fetch data from my database, but its capabilities are limited. Currently it can fetch one value at a time, which is fine for fetching the value of one column of one row, but as I progress with my work, I now want to be able to fetch multiple values in one call.
The Function:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data[$value];
}
mysqli_close($connection);
}
How I currently use it to fetch multiple values:
// Define variables
$x1 = retrieve("x1");
$x2 = retrieve("x2");
$x3 = retrieve("x3");
$x4 = retrieve("x4");
$x5 = retrieve("x5");
$x6 = retrieve("x6");
$x7 = retrieve("x7");
$x7 = retrieve("x8");
I have read other questions here on Stack Overflow, but none of them solves my problem as I use an optional parameter, which makes my life hard. For example, I thought of implementing the splat operator to allow unlimited parameters, but as I use the optional parameter $identifier, I can't make it into something like:
function retrieve($identifier = null, ...$value) {}
because it will use the first parameter as the identifier when I omit it.
I'm sure that regarding performance it would be better if I could fetch all the necessary values in one call of the function retrieve() instead of using it as shown above and that's why I would like to know:
How can I edit this function in order to fetch more values at once?
Calling it like so:
$x = retrieve($y);
$x1 = $y["x1"];
$x2 = $y["x2"];
...
EDIT:
Thanks to Manish Jesani for his help! I used his answer and modified to do exactly what I want. For anyone that may be interested in the future, here's the code:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$values = array();
$identifier = (is_null($identifier)) ? "`ID` = '1'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if (is_array($value)) {
foreach($value as $_value) {
$values[$_value] = $data[$_value];
}
return $values;
}
else {
return $data[$value];
}
}
mysqli_close($connection);
}
You can call the function with as many parameters you want. Τo do this you have to use func_num_args() to get all of them, as shown below:
function retrieve() {
$args = func_num_args();
$query = "SELECT '".implode("','", func_get_args())."' FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data;
}
mysqli_close($connection);
}
You can call this function like this: $params = retrieve('x1','x2','x3').
Alternatively, you can retrieve them as variables list($x1, $x2, $x3) = retrieve('x1','x2','x3').
Please try this:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$return = array();
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if(is_array($value))
{
foreach($value as $_value)
{
$return[$_value] = $data[$_value];
}
}
else
{
$return[$value] = $data[$value];
}
return $return;
}
mysqli_close($connection);
}
$x = retrieve(array("x1","x2","x3","x4","x5","x6"));

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.

how to make function in php with mysql result?

I am using same query again and again on different pages in between to fetch result. I want to make a function for this query.
$result = mysql_query(" SELECT name FROM tablename where id= '$row[name_id]'");
$row = mysql_fetch_array($result);
echo $row ['name'];
How to make and how to call the function?
sample class stored sample.php
class sample
{
function getName(id)
{
$result = mysql_query("SELECT name FROM tablename where id='$id'");
$row = mysql_fetch_array($result);
return $row ['name'];
}
}
use page include sample.php,then create object,then call getName() function.
<?php
include "db.class.php";
include "sample.php";
$ob=new sample(); //create object for smaple class
$id=12;
$name=$ob->getName($id); //call function..
?>
This is a good idea but first of all you have to create a function to run queries (as you have to run various queries way more often than a particular one)
function dbget() {
/*
easy to use yet SAFE way of handling mysql queries.
usage: dbget($mode, $query, $param1, $param2,...);
$mode - "dimension" of result:
0 - resource
1 - scalar
2 - row
3 - array of rows
every variable in the query have to be substituted with a placeholder
while the avtual variable have to be listed in the function params
in the same order as placeholders have in the query.
use %d placeholder for the integer values and %s for anything else
*/
$args = func_get_args();
if (count($args) < 2) {
trigger_error("dbget: too few arguments");
return false;
}
$mode = array_shift($args);
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val) {
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
if (!$query) return false;
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return false;
}
if ($mode === 0) return $res;
if ($mode === 1) {
if ($row = mysql_fetch_row($res)) return $row[0];
else return NULL;
}
$a = array();
if ($mode === 2) {
if ($row = mysql_fetch_assoc($res)) return $row;
}
if ($mode === 3) {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
then you may create this particular function you are asking for
function get_name_by_id($id){
return dbget("SELECT name FROM tablename where id=%d",$id);
}
You should probably parse the database connection as well
$database_connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');
function get_row_by_id($id, $database_link){
$result = mysql_query("SELECT name FROM tablename where id= '{$id}");
return mysql_fetch_array($result);
}
Usage
$row = get_row_by_id(5, $database_connection);
[EDIT]
Also it would probably help to wrap the function in a class.
function getName($id){
$result = mysql_query("SELECT name FROM tablename where id= '$row[name_id]'");
$row = mysql_fetch_array($result);
return $row ['name'];
}
call the function by
$id = 1; //id number
$name = getName($id);
echo $name; //display name

Categories