How to fetch assoc in mysqli without foreach or while? - php

In mysql, we use
$userdata = mysql_fetch_assoc(mysql_query("select * tablename where id=".$_SESSION['user_id']."));
And then we can use $userdata anywhere on that page....
How can we do it with mysqli without using foreach or while statement ?
What I have tried is
<?
include ("db.php");
session_start();
if(isset($_SESSION['user_id']))
{
$userid = $_SESSION['user_id'];
$query = "SELECT * FROM mytable where id= '$userid'";
$userdataraw = $database->get_results($query);
$userdata = $userdataraw ->fetch_assoc();
}
?>
Class Used as :
public function get_results( $query, $object = false )
{
self::$counter++;
//Overwrite the $row var to null
$row = null;
$results = $this->link->query( $query );
if( $this->link->error )
{
$this->log_db_errors( $this->link->error, $query );
return false;
}
else
{
$row = array();
while( $r = ( !$object ) ? $results->fetch_assoc() : $results->fetch_object() )
{
$row[] = $r;
}
return $row;
}
}
When I tried This, I got error
Fatal error: Call to undefined function fetch_assoc()
I want set $userdata without foreach or while, is it possible in Mysqli??

The get_resultsfunction already returns an associative array if the second parameter is not set or false. Thus there is no need to call fetch_assoc() again.
Also if you only expect a single dataset and don't want to use a loop you would need to do something like this: $userdata = $userdataraw[0]to get the first and only dataset.

Related

Array in while loop

I created a function that read data from a mysql db.
I want to put the data into a array and read that outside of the PHP function.
function showCategory($con) {
$sql = "SELECT * FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
return $kategorien;
}
}
To load the data outside from function:
$kategorien = showCategory($con);
echo $kategorien['kategorie'][0];
It doesn't work. Whats wrong?
The
return $kategorien;
will exit the loop and the function, so move this to the end of the function and not in the loop.
function showCategory($con) {
$sql = "SELECT kategorie FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
}
return $kategorien;
}
Rather than using *, it's also worth specifying the column names if you only need some of them.
Display the data using...
$kategorien = showCategory($con);
print_r( $kategorien );
or use a foreach()...
$kategorien = showCategory($con);
foreach ( $kategorien as $kat ) {
echo $kat.PHP_EOL;
}
Use this instead, because returning $kategorien will exit the loop, so it will only run once.
function showCategory($con) {
$sql = "SELECT * FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
}
return $kategorien;
}

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 can I create a function out my php select? [duplicate]

This question already has answers here:
Setting a function equal a variable?
(3 answers)
Closed 8 years ago.
How can I create a function out of my php select? Here is the code:
<?
$sql = "SELECT value FROM configuration WHERE name = 'website_name'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
?>
<?=$row['value'];?>
Basically I want to turn it into a function and call it as a variable so something like this. Here is the code:
<?
function ItsaFunction() {
//code goes here
}
?>
I want to output the code as a variable. Here is the code:
<?=$ItsaFunction?>
How can I convert my select to a function and call it as a variable?
So you want...
<?php
function ItsaFunction() {
$sql = "SELECT value FROM configuration WHERE name = 'website_name'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
return $row['value'];
}
?>
And then use
<?=ItsaFunction()?>
?
Try this
function yourfunc($sitename)
{
$sitename = mysql_real_escape_string($sitename);
$sql = "SELECT value FROM configuration WHERE name = '$sitename'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
return $row['value'];
}
This is a simple transformation of your code to a function so you can call it. But you should do a bit more with that code, like check for results, initialize variables, etc ...
function get_website( $website_name = false ) {
if ( $website_name === false ) {
return false;
} else {
$sql = "SELECT value FROM configuration WHERE name = $website_name";
$result = mysql_query( $sql );
$row = mysql_fetch_assoc( $result ); // assuming you have results on row
return $row.
}
}
You will call that function this way
$website_information = get_website( 'name_of_the_website_you_are_looking_for' );
And the you will use $website_information according to what you want and what information is on that variable.

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

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