how to make function in php with mysql result? - php

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

Related

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"));

How to get multiple rows from mysql & PHP with this function

I have this function which returns only one row, How can I modify the function so that it returns more than one row?
public function getVisitors($UserID)
{
$returnValue = array();
$sql = "select * from udtVisitors WHERE UserID = '".$UserID. "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
There is a function in mysqli to do so, called fetch_all(), so, to answer your question literally, it would be
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ".intval($UserID);
return $this->conn->query($sql)->fetch_all();
}
However, this would not be right because you aren't using prepared statements. So the proper function would be like
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $UserID);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_all();
}
I would suggest storing them in an associative array:
$returnValue = array();
while($row = mysqli_fetch_array($result)){
$returnValue[] = array('column1' => $row['column1'], 'column2' => $row['column2']); /* JUST REPLACE NECESSARY COLUMN NAME AND PREFERRED NAME FOR ITS ASSOCIATION WITH THE VALUE */
} /* END OF LOOP */
return $returnValue;
When you call the returned value, you can do something like:
echo $returnValue[0]['column1']; /* CALL THE column1 ON THE FIRST SET OF ARRAY */
echo $returnValue[3]['column2']; /* CALL THE column2 ON THE FOURTH SET OF ARRAY */
You can still call all the values using a loop.
$counter = count($returnValue);
for($x = 0; $x < $counter; $x++){
echo '<br>'.$rowy[$x]['column1'].' - '.$rowy[$x]['column2'];
}

php class return array

I tried to get followers from MySQL usingy this class
class get_followers {
public $followers_arr = array();
public function __construct($user_id) {
$query = "select * from followsystem where following ='$user_id'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($this->followers_arr, $row['userid']);
}
}
return $this->followers_arr;
}
}
Then I initialize this class
$fol = new get_followers($userid);
$fol_arr = json_encode($fol);
echo $fol_arr;
Then I get
{"followers_arr":["1234","456"]}
but what i want want just to get this
["1234","456"]
How is that works?
I don't think you understand how constructors work. You can't return a value from a constructor because it's just used to instantiate the object. When you're doing $fol_arr = json_encode($fol); you're actually encoding the entire object, not it's return value.
If you really want to use a class to do this, you should add a method to the class and use that, like this:
class Followers {
public $followers_arr = array();
public $user_id = null;
public function __construct($user_id) {
$this->user_id = $user_id;
}
public function get()
{
$query = "select * from followsystem where following ='{$this->user_id}'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($this->followers_arr, $row['userid']);
}
}
return $this->followers_arr;
}
}
And use it like this:
$fol = new Followers($userid);
$fol_arr = json_encode($fol->get());
echo $fol_arr;
The solution to your problem is to do $fol_arr = json_encode($fol->followers_arr);
Nonetheless, making a class in this case is completely obsolete, since you only make it as a wrapper for a single function you want to execute (called get_followers) Instead of making a class, you could simply make the following:
function get_followers($user_id) {
$followers_arr = [];
$query = "select * from followsystem where following ='$user_id'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($followers_arr, $row['userid']);
}
}
return $followers_arr;
}
$fol = get_followers($userid);
$fol_arr = json_encode($fol);
echo $fol_arr;
There is no need to put it in a class unless the class serves the purpose of combining a few functions and variables to create a behaviour.

PHP issue using a method's return value as a parameter for query function

I have a function query:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
The function works just fine when I use it like this:
$g = "05%";
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $g);
print json_encode($result);
However I am getting no result when $g is a value retrieved from a method. For example lets say I have a method getMonth() from a class Date that returns the current month of May as 05% when echoed. I try the code below and get nothing from the database:
$time = new Date();
//$g = "05%"; this would definitely get results from the db
$h = $time->getMonth();
echo $h; //this displays 05% on the screen
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $h);
print json_encode($result);
I am pretty sure that I am making a simple mistake, but I can't seem to figure it out. How can I fix this? Any help would be greatly appreciated.
Do something that your method return only 05 part from 05%. and append % after that for example
$h = $time->getMonth();
$h = "$h%";
and then it should work

PHP: letting your own function work with a while loop

$qVraagGroepenOp = "SELECT * FROM $tabele WHERE $where";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
$aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp )
and I converted that to a function
vraagOp("testtable","testtable_ID = $id");
function vraagOp($table,$where)
{
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
$aVraagOp = mysql_fetch_assoc( $rVraagOp );
return $aVraagOp;
}
only the problem is when i need more then one row i need to use a while loop
$qVraagGroepenOp = "SELECT * FROM testtable where testtype = test";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
while ( $aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp ) )
{
echo "testing <br>";
}
It wont work anymore is there a trick to make my function work with this while loop?
This won't work but I want to reach to something like it
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
Is this possible?
This could be done with static variables in the function scope.
function vraagOp($table,$where)
{
static $rVraagOp;
if(!$rVraagOp){
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
}
return mysql_fetch_assoc( $rVraagOp );
}
That should do what you're after.
This function returns an array of rows - it's a generic pattern yu can use almost anywhere you get multiple rows from a query.
function vraagOp($table,$where)
{
$sql= "SELECT * FROM $table WHERE $where";
$query= mysql_query($sql);
if ($query != false)
{
$result = array();
while ( $row = mysql_fetch_assoc($query) )
$result[] = $row;
return $result;
}
return $false;
}
//usage
$rows = vraagOp($table,$where);
if ($rows)
{
foreach ($rows as $row)
use($row);
}
This function will 'cache' the mysql result resource from each unique $table/$where combination, and fetch the next result from it on each subsequent call. It will return an associative array for each row, or false when there are no rows left.
function vraagOp($table, $where)
{
// Holds our mysql resources in a map of "{$table}_{$where}" => resource
static $results = array();
$key = $table . '_' . $where;
if (!isset($results[$key]))
{
// first call of this particular table/where
$results[$key] = mysql_query("SELECT * FROM $table WHERE $where");
}
$row = mysql_fetch_assoc($results[$key]);
if ($row === false)
// remove this key so a subsequent call will start over with a new query
unset($results[$key]);
return $row;
}
// Usage
while ($row = vraagOp("table1", "where field > 7")) {
print_r($row);
}
This
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
will work if you change VraagOp() to return false when no matching record was found.
You would have to move the mysql_query() part out of VraagOp(), and just leave the mysql_fetch_assoc part in.
However, I can't really see what benefit there would be? You would just be building a (unnecessary) wrapper around mysql_fetch_assoc(), wouldn't you?
You'll need to turn vraagOp() into an iterator and then use foreach() in order to make this work.
Your example won’t work because the condition is executed on every iteration. That means vraagOp("testtable","testtype = test") would be called with each iteration until it returns a falsely value. mysql_fetch_assoc does that but your function doesn’t.
How can we call function inside while loop example is below :
$sql_gpfsF="SELECT * FROM emp_salary";
$result_gpfsF=mysql_query($sql_gpfsF);
while($row_gpfsF=mysql_fetch_assoc($result_gpfsF))
{
call_function();
}
function call_function()
{
echo " Function Called </ br>";
}

Categories