Call MySql Select Query in 2 different php function - php

Please help me with my problem.. can i call once Mysql Select Query from different function from two different function too... Sorry i don't know how to explain.. but below my sample what i want to archive..
I want use single query for 2 function.. so maybe i have to write code like below?
function sqlSelect ($db, $id, $id2) {
$sql = mysqli_query($db, "SELECT * FROM xxx WHERE id='$id' AND id2='$id2'");
$row = mysqli_num_rows($sql);
$field = mysqli_fetch_object($sql);
return $row;
}
but how to use $field inside 2 diff function?
function aaa ($a,$b,$c) {
if($row >= 1){
//Do something with $a $b and $c
//$reget field with $field['column'];
$field['column']; //???
}
return $result;
}
function bbb ($a,$b,$c) {
if($row >= 1){
//Do something with $a $b and $c
//get field with $field['column'];
$field['column']; //???
}
}
what i do right now is
function aaa ($db,$id,$id2,$a,$b,$c) {
$sql = mysqli_query($db, "SELECT * FROM xxx WHERE id='$id' AND id2='$id2'");
$row = mysqli_num_rows($sql);
$field = mysqli_fetch_object($sql);
if($row >= 1){
//Do something with $a $b and $c
//get field with $field['column'];
}
}
function bbb ($db,$id,$id2,$a,$b,$c) {
$sql = mysqli_query($db, "SELECT * FROM xxx WHERE id='$id' AND id2='$id2'");
$row = mysqli_num_rows($sql);
$field = mysqli_fetch_object($sql);
if($row >= 1){
//Do something with $a $b and $c
//get field with $field['column'];
}
}
But if i use what i write and code right now i think it's have to call same query twice. I cannot use query outside function so i have to write query on each function but i want to just write query once and can use in two different function..
Sorry for stupid explanation..
Thank you for help

One implementation can be as follow by passing an array as argument,
<?php
$arg['db']="database";
$arg['tabe']="table";
$arg['search']['id1']="id1";
$arg['search']['id2']="id2";
$arg['do_something']['a']="a";
$arg['do_something']['b']="b";
$arg['do_something']['c']="c";
function searchAndDoSomethingAndReturnResult($arg)
{
$return = NULL;
$query="SELECT * FROM ".$arg['table'];
$flag=false;
foreach($arg['search'] as $key=>$value)
{
if($flag)
$query.=" AND ";
else
$flag=true;
$query.= $key." = '".$value."' ";
}
$row = mysqli_num_rows($query);
$field = mysqli_fetch_object($query);
if($row >= 1)
{
foreach($arg['do_something'] as $job=>$value)
{
// $return[] = "some result"
// do something
}
}
return $return;
}
?>
let me know if this solve your problem

You can either pass in the $field variable as a function argument
<?
$field = ...;
function sql1($field,...,...){
// Use $field here
}
function sql2($field,...,...){
// Use $field here
}
?>
Alternatively, you can use the global keyword to access variables from outside of the function
<?
$field = ...;
function sql1(){
global $field;
// Use $field here
}
function sql2(){
global $field;
// Use $field here
}
?>

Related

Geting a maximum value in code iginiter function

I'm using this function to recover a maximum value in a table in code igniter. But it's returning no value. Actually it's recovering a null value from the table, and I think it is not dealing with a variable as integer. Here is my code:
public function MaxWork($n)
{
$this->db->select_max('w_no');
$this->db->where('n_no', $n);
$query = $this->db->get('t_detail');
foreach ($query->result() as $row)
{
$no = $row->w_no;
}
if($no == '')
$no = 1;
return($no);
}
}
public function MaxWork($n)
{
$this->db->select_max('w_no');
$this->db->where('n_no', $n);
$this->db->group_by('n_no');
$query = $this->db->get('t_detail');
if($query->num_rows() > 0)
return $query->row()->w_no;
else
return 1; // default 1 as per your requirement for null records
}
no need for foreach

php variable scope inside a loop in a function

I am wondering is there any way to get the value of a variable, that was defined in a loop inside a function?
Do variables declared in a loop / if-then-else, etc have a limited scope (only inside these blocks)?
here is an example of a function:
<?php
function getComments($tabName) {
$sql = "select
a.owner,
a.table_name,
a.column_name,
a.data_type,
a.data_length,
a.data_precision,
b.comments
from
all_tab_columns a,
user_col_comments b
where
a.TABLE_NAME = b.table_name
and a.COLUMN_NAME = b.column_name
and a.owner = 'CORE'
and a.table_name ='" . $tabName . "'
order by
a.column_id";
$stid = oci_parse(getConnect(), $sql);
// runs the query above
oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
foreach ($row as $column => $entry) {
// Column name
if ($column == 'COLUMN_NAME') {
$output = "this is a column";
}
}
}
return $output;
}
And here I get the "Undefined variable: output" error.
if I put echo instead the $output variable, I get the result.
Is it because the $output scope? How can I get the $output value in my return?
try to satisfy this condition
if ($column == 'COLUMN_NAME') {
$output = "this is a column";
}
and also u can try to return immediately after ur condition
if ($column == 'COLUMN_NAME') {
return "this is a column";
}

Can i store an selected value in variable

Is it possible to store an select value into an variable? in codeigniter.
Something like this:
$this->db->select_max('Datum');
$this->db->from('Uren');
$this->db->join('Project','Project.idProject = Uren.idProject');
$test123 = $this->db->get();
So that i get the value of the select_max into the variable $test123
The proprer way, then $max will contain the max of your request, or FALSE if request is not valid :
$query = $this->db->select_max('Uren.Datum', 'max_Datum')->get('your_table');
$max = $query ? $query->row()->max_Datum : FALSE;
I think you need to do something like this.
$this->db->select_max('Uren.Datum');
$test = $this->db->get('table_name');
if ($test) {
$this->db->select('fields');
$this->db->group_by('Project.idProject');
$this->db->get('table_name');
}
these will be two separate quires.
try
$this->db->select_max('field_name');
$check_query = $this->db->get('table_name');
if ($check_query->num_rows() > 0) {
$max = $check_query->result();
if(!empty($max[0]->field_name)) {
}
}
for more :- https://www.codeigniter.com/userguide2/database/active_record.html
This is the answer that worked to my question. Hope it will help someone else too
$this->db->select_max('Datum');
$this->db->from('Uren');
$this->db->join('Project','Project.idProject = Uren.idProject');
if ($idKlant > 0){
$this->db->where('idKlant', $idKlant);}
$datumstart = $this->db->get();
foreach ($datumstart->result() as $row)
{
$datastart = $row->Datum;
}

using a $_GET id to filter a mysql_fetch_array in PHP

So I have a query that I am returning all of the items into a mysql_fetch_array. Now, I know I could write another query and just select the items I need into a seperate query but, is there a way to just filter from the larger query what I want dependent on $_GET?
So, in english the user comes from a hyperlink that has ?id=1 and I peform a while that gets the all the values but, only display the $_GET['id'] items in a list
<?php //give ma all values but only echo out list of the $_GET['id'] in the url
while ($row = mysql_fetch_array($result) {
$id = $rowvideo["id"];
$title = $rowvideo["title"];
$length = $rowvideo["length"];
}
echo("<li><a href='#'>". $title." " .$length. "</a></li>");
?>
Hope this makes sense. Thank you all.
If you do not want a second query to get just what you need, a simple-if-statement in your loop should work:
<?php
$getId = isset($_GET['id']) ? $_GET['id'] : false;
//give ma all values but only echo out list of the $_GET['id'] in the url
while ($row = mysql_fetch_array($result)) {
$id = $row["id"];
$title = $row["title"];
$length = $row["length"];
if ($id == $getId) {
echo("<li><a href='#'>". $title." " .$length. "</a></li>");
}
}
?>
Note that I declared $getId outside of the loop to prevent having to use isset() during every iteration. If you don't verify if it's set and attempt to use it it will throw an undefined index warning - assuming you have error_reporting turned on (with that level enabled).
Alternatively, you could use PHP's array_filter() on the data after you've parsed it all:
$results = array();
while ($row = mysql_fetch_array($result)) $results[] = $row;
if (isset($_GET['id'])) {
$filtered = array_filter($results, function($element) use ($_GET['id']) { return ($element['id'] == $_GET['id']); });
$results = $filtered;
}
foreach ($results as $result) {
echo("<li><a href='#'>". $result['title']." " .$result['length']. "</a></li>");
}
My personal opinion would be to be more efficient and write the second query though, assuming of course you don't actually need all of the results when an id is specified. It would be as simple as:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$query = 'SELECT id, title, length FROM table WHERE id=' . (int)$_GET['id'];
} else {
$query = 'SELECT id, title, length FROM table';
}
// your existing code as-is
A little more clarity here:
This will allow the filter by id in the url by specifying id=xxx, IF xxx is an integer that is positive. So id of 'bob' or -1 will not filter the results still giving all results
$filter=false;
if(isset($_GET['id']))
{
$filter_id=intval($_GET['id']);
if($id>0) $filter=true;
}
while($row = mysql_fetch_array($result))
{
if( (!$filter) || ( ($filter) && ($filter_id==$row['id']) ) )
{
$id = $row["id"];
$title = $row["title"];
$length = $row["length"];
// do other stuff here
}
}
I also changed $rowvideo to $row as this is the array you used to fetch the results.
<?php //give ma all values but only echo out list of the $_GET['id'] in the url
while ($row = mysql_fetch_array($result)) {
$id = $rowvideo["id"];
$title = $rowvideo["title"];
$length = $rowvideo["length"];
if ($id == $_GET['id']) { // or even ===
echo("<li><a href='#'>". $title." " .$length. "</a></li>");
}
}
?>

MySQLi equivalent of mysql_result()?

I'm porting some old PHP code from mysql to MySQLi, and I've ran into a minor snag.
Is there no equivalent to the old mysql_result() function?
I know mysql_result() is slower than the other functions when you're working with more than 1 row, but a lot of the time I have only 1 result and 1 field. Using it lets me condense 4 lines into 1.
Old code:
if ($r && mysql_num_rows($r))
$blarg = mysql_result($r, 0, 'blah');
Desired code:
if ($r && $r->num_rows)
$blarg = $r->result(0, 'blah');
But there is no such thing. :(
Is there something I'm missing? Or am I going to have to suck it up and make everything:
if ($r && $r->num_rows)
{
$row = $r->fetch_assoc();
$blarg = $row['blah'];
}
The following function fully replicates the mysql_result() function, and returns false when you are out-of-bounds on your request (empty result, no row of that number, no column of that number). It does have the added benefit that, if you don't specify the row, it assumes 0,0 (one less value to be passed). The function allows for the numerical offset of the field or the field name.
function mysqli_result($res,$row=0,$col=0){
$numrows = mysqli_num_rows($res);
if ($numrows && $row <= ($numrows-1) && $row >=0){
mysqli_data_seek($res,$row);
$resrow = (is_numeric($col)) ? mysqli_fetch_row($res) : mysqli_fetch_assoc($res);
if (isset($resrow[$col])){
return $resrow[$col];
}
}
return false;
}
PHP 5.4 now supports function array dereferencing and 7.0 supports a null coalescing operator, which means you can simply do this:
$value = $r->fetch_assoc()['blah'] ?? false;
or even more generic variant where you don't need to supply the column name,
$value = $r->fetch_row()[0] ?? false;
note that you don't even need the if ($r && $r->num_rows) condition.
You can do this by fetching an object instead of an array.
$mysqli->query("SELECT email FROM users WHERE userid = 'foo'")->fetch_object()->email;
function db_result($result,$row,$field) {
if($result->num_rows==0) return 'unknown';
$result->data_seek($row);
$ceva=$result->fetch_assoc();
$rasp=$ceva[$field];
return $rasp;
}
Well, you can always shorten it to something like this:
if ($r && $r->num_rows)
list($blarg) = $r->fetch_row();
But that might be as good as you're going to get.
I suggest you to add this line to Cris' solution in order to be able to get a result by both doing db_result('mytable.myfield) and db_result('myfield') since it is the default behavior of the original mysql_result function.
function db_result($result,$row,$field) {
if($result->num_rows==0) return 'unknown';
$result->data_seek($row);
$ceva=$result->fetch_assoc();
return (isset($ceva[$field])?$ceva[$field]
:(strpos($field,'.')?$ceva[substr($field,strrpos($field,'.')+1)]:''));
}
I use the following function to replace mysql_result()
function mysqli_result($result, $iRow, $field = 0)
{
if(!mysqli_data_seek($result, $iRow))
return false;
if(!($row = mysqli_fetch_array($result)))
return false;
if(!array_key_exists($field, $row))
return false;
return $row[$field];
}
I ended up using a custom function using procedural style:
function mysqli_result($res, $row, $field=0) {
mysqli_data_seek($res, $row);
return mysqli_fetch_array($res)[$field];
}
Reference: https://www.sitepoint.com/community/t/change-mysql-result-to-mysqli/190972/6
You don't need mysql_result() or any similar function.
If you would like to access any column from any row in the result set, the best way is to fetch all into an array using mysqli_fetch_all().
$data = $result->fetch_all(MYSQLI_BOTH);
$var1 = $data[0]['column']; // column from the first row
$var2 = $data[1][2]; // third column from the second row
To prevent access to non-existent values, you can use the null-coalesce operator and provide default value. e.g. $data[1][2] ?? null;.
As of PHP 8.1, mysqli also offers method called fetch_column(). You can use it if you only want to fetch a single value from the result.
$value = $mysqli->query("SELECT email FROM users WHERE userid = 'foo'")->fetch_column(0);
If you select only ONE field in the query and you only expect a single returned data of a selected field, then this works:
function mysqli_datum($result)
{
if ($result->num_rows == 0)
return;
$result->data_seek(0);
$row=$result->fetch_row();
return $row[0];
}
Here's an adaptation of Mario Lurig's answer using a mysqli_result object instead of the procedural version of mysqli.
/**
* Accepts int column index or column name.
*
* #param mysqli_result $result
* #param int $row
* #param int|string $col
* #return bool
*/
function resultMysqli(mysqli_result $result,$row=0,$col=0) {
//PHP7 $row can use "int" type hint in signature
$row = (int)$row; // PHP5 - cast to int
if(!is_numeric($col) ) { // cast to string or int
$col = (string)$col;
} else {
$col = (int)$col;
}
$numrows = $result->num_rows;
if ($numrows && $row <= ($numrows-1) && $row >=0) {
$result->data_seek($row);
$resrow = (is_numeric($col)) ? $result->fetch_row() : $result->fetch_assoc();
if (isset($resrow[$col])){
return $resrow[$col];
}
}
return false;
}
This is a good answer, from http://php.net/manual/es/class.mysqli-result.php
<?php
function mysqli_result($result,$row,$field=0) {
if ($result===false) return false;
if ($row>=mysqli_num_rows($result)) return false;
if (is_string($field) && !(strpos($field,".")===false)) {
$t_field=explode(".",$field);
$field=-1;
$t_fields=mysqli_fetch_fields($result);
for ($id=0;$id<mysqli_num_fields($result);$id++) {
if ($t_fields[$id]->table==$t_field[0] && $t_fields[$id]->name==$t_field[1]) {
$field=$id;
break;
}
}
if ($field==-1) return false;
}
mysqli_data_seek($result,$row);
$line=mysqli_fetch_array($result);
return isset($line[$field])?$line[$field]:false;
}
?>

Categories