$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>";
}
Related
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;
}
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.
I am attempting to return all of the rows in a MySQL table. I have the following function:
function listTickets() {
global $con;
$result = mysqli_query($con, "SELECT * FROM tickets");
while($row = mysqli_fetch_array($result)) {
return array($row['subject'], $row['category'], $row['username'], $row['last'], $row['id', $row['status']);
}
mysqli_close($con);
}
However, print_r(listTickets()) does not return all rows, only the first row. How can I make it so that it will return every row? I know how to do it without using functions and whatnot, but I'd like to figure out how to do it with the function. Thanks!
When you use 'return', your function will return immediately - the first time round the loop. Subsequent runs through the loop are cancelled, as is the mysqli_close.
Also: (1) you are closing the database connection for everyone else (as a rule of thumb, if you open it, close it; if you don't open it, don't close it), and (2) $result isn't the finale result - consider using a more descriptive variable
So then it looks like this:
function listTickets()
{
global $con;
$query = mysqli_query($con, "SELECT * FROM tickets");
$result = array();
while($row = mysqli_fetch_array($query))
{
array_push($result,array($row['subject'], $row['category'], $row['username'], $row['last'], $row['id', $row['status']));
}
return $result;
}
Next, I would add the option MYSQLI_NUM (or even MYSQLI_ASSOC) to mysqli_fetch_array, and remove the code which takes an array, and converts it into almost exactly the same array.
function listTickets()
{
global $con;
$query = mysqli_query($con, "SELECT * FROM tickets");
$result = array();
while($row = mysqli_fetch_array($query,MYSQLI_NUM))
{
array_push($result,$row);
}
return $result;
}
once you use return in a function, the function is ended and the value after return is returned.
Therefore, you need to store your database row somewhere and then at the end return all stored rows.
e.g.:
function listTickets()
{
global $con;
$result = mysqli_query($con, "SELECT * FROM tickets");
$stack = array(); // <- the temp array
while($row = mysqli_fetch_array($result))
{
// push the db result to the stack
array_push($stack, $row);
}
mysqli_close($con);
return $stack;
}
Once a return statement is reached, the function is completed. You will need to gather the rows into some sort of collection and return the collection of rows.
Hope this helps
return exits the function immediately. Accumulate the output in the buffer then return it:
function listTickets()
{
global $con;
$result = mysqli_query($con, "SELECT * FROM tickets");
buffer = array();
while($row = mysqli_fetch_array($result))
{
array_merge(buffer,array($row['subject'], $row['category'], $row['username'], $row['last'], $row['id', $row['status']));
}
mysqli_close($con);
return buffer;
}
This is what I have so far. It calls to the database and receives one comment and all of the values that go with it, but I want to get multiple comments with the same id. How do I set up a array to get the multiple comments?
function get_comment_by_id($lake_id) {
global $connection;
$query = "SELECT * ";
$query .= "FROM comments ";
$query .= "WHERE lakeId=" . $lake_id ." ";
//$query .= "LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
// REMEMBER:
// if no rows are returned, fetch_array will return false
if ($comment = mysql_fetch_array($result_set)) {
return $comment;
} else {
return NULL;
}
}
you just need to put it in a while loop. instead of
if ($comment = mysql_fetch_array($result_set)) {
return $comment;
} else {
return NULL;
}
do
$rows = array();
while($comment = mysqli_fetch_array($result_set))
$rows[] = $comment;
return $rows;
and you also need to use mysqli_* functions since the mysql_* functions are deprecacted.
In the calling function you should check for an empty array instead of a null value
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