How can I create a function out my php select? [duplicate] - php

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.

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;
}

MySQL query variable not accepted

I am working on a PHP script that should get data from MySQL.
Here is what am I doing:
<?php
include('db.php');
session_start();
$doctor_actual=$_SESSION['doctor_actual'];
echo $doctor_actual;
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$con,$limit,$adjacent);
}
function showData($data,$con,$limit,$adjacent){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$sql = "select * from tb_opiniones_doctor where codigo_verificacion = '".$doctor_actual."' order by id_opinion_doctor asc";
$rows = $con->query($sql);
$rows = $rows->num_rows;
$sql = "select * from tb_opiniones_doctor where codigo_verificacion = '".$doctor_actual."' order by id_opinion_doctor asc limit $start,$limit";
$data = $con->query($sql);
$str='<table><tr class="head"><td>Id</td><td>Firstname</td><td>Lastname</td></tr>';
if($data->num_rows>0){
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
$str.="<tr><td>".$row['id_opinion_doctor']."</td><td>".$row['id_opinion_doctor']."</td><td>".$row['id_opinion_doctor']."</td></tr>";
}
}else{
$str .= "<td colspan='5'>No Data Available</td>";
}
$str.='</table>';
echo $str;
pagination($limit,$adjacent,$rows,$page);
}
My problems are at the two queries, they only work if I put the real value for $doctor_actual, not as variable.
I have echoed the value for $doctor_actual, it is 9dv2ACvtwn2.
If I put in the queries ..where codigo_verificacion = "9dv2ACvtwn2"... the queries work fine.
If I put:
codigo_verificacion = '".$doctor_actual."'
or
codigo_verificacion = '.$doctor_actual.'
or
codigo_verificacion = $doctor_actual
it shows the message:
No Data Available
You should read about Variable scope. $doctor_actual outside function and $doctor_actual inside function are two different variables. As you can read above something like that
<?php
$var = 'text';
function myFunc()
{
global $var;
echo $var; // 'text'
}
will solve your problem.
But as noticed #Sean in comments below it's better idea to pass value as a parameter. Just add additional parameter to your function and pass value during function call.

How to fetch assoc in mysqli without foreach or while?

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.

How to 'append' function variables using the URL and a question about Array's

The first question is how to run a function using the URL, I have the following function:
function do_curl($start_index,$stop_index){
// Do query here to get all pages with ids between start index and stop index
$query = "SELECT * FROM xxx WHERE xxx >= $start_index and xxx <= $stop_index";
Now when I'm trying to do curl.php?start_index=0&stop_index=2 this is not working but when i delete the function and WHERE idnum = 1 it is working.
Now the second question is how 'compile' all the fields from the rows to arrays? I have the current code:
$query = "SELECT * FROM fanpages";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query = '\'http://graph.facebook.com/'.$row['page_id'].'\', ';
echo $fanpages_query;
}
$fanpages = array($fanpages_query);
$fanpages_count = count($fanpages);
echo $fanpages_count;
echo $fanpages_query; returning
'http://graph.facebook.com/AAAAAA', 'http://graph.facebook.com/BBBBBBB', 'http://graph.facebook.com/CCCCCCCC',
(I don't have an idea how to do it in a different way, also when im doing it in such a way i can't delete the final comma which will return PHP-error.)
echo $fanpages_count; returns 1 and like you can see i have 3 there.
Thanks in advance guys!
Do a function call to do the query
function do_curl($start_index, $stop_index){
...
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
For your second question, you can use arrays and the implode function to insert commas:
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
Then use implode to print them out:
echo implode(',', $fanpages);
The whole code:
function do_curl($start_index = 0, $stop_index = null) {
$queryIfThereIsNoStartIndex = '';
$queryIFThereIsNoStopIndex = '';
$queryIfBothStartAndStopIndexAreMissing = '';
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
$fanpages_count = count($fanpages);
echo implode(',', $fanpages);
And you should totally use mysql_escape_string for escaping the values you add to the query.

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