Reputation: 41
I want to pass the name of field and table as an argument in php function so that i can use those values in my query.
function finder($v1, $v2){
$mid=0; $nid=-5; $v11='go';
include'connect.php';
$query1=mysqli_query($con, "SELECT MAX(id) FROM users_allow");
WHILE($row=mysqli_fetch_array($query1))
{
$mid = $row['0'];
}
}
finder('id', 'users_allow');
How the query should be changed to adopt the name of field and the table from the arguments passed to the function. i had tried v1, v2 in single quote in the query but does not work, Problem remain as how to use these two variable (v1 and v2) as filed name and table name in MySQL Query.
Upvotes: 1
Views: 524
Reputation: 267
You can use either of following
function finder($v1, $v2){
$mid=0; $nid=-5; $v11='go';
include'connect.php';
//way one:
$query1=mysqli_query($con, sprintf("SELECT MAX(%d) FROM %s",$v1,$v2));
//way two: this will only work with the string inside ""
$query1=mysqli_query($con, "SELECT MAX({v1}) FROM {$v2}");
WHILE($row=mysqli_fetch_array($query1))
{
$mid = $row['0'];
}
}
finder('id', 'users_allow');
Upvotes: 1