php - function return values dynamically - php

I want to return a set of values from function till the point they exist....
for example....
function abc($i="3"){
for($a=1;$a<=$i;$a++) {
$name='t'.$i;
$$name = "ae".$a;
}
//now i am returning values
return array($t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10);
//but i only want to return $t1,$t2,$t3 depending on $i
}
Thanks....
#therefromhere
I am also creating an array in the loop , I'll paste the original code so that you can understand it in a better way
function extracting_comments($table, $fields,$condition,$order,$limit){
$query="SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
$params = array();
foreach($row as $k=>$v) {
$params[] = &$row[$k];
echo $params[0];
}
call_user_func_array(array($stmt,'bind_result'),$params);
$i=0;
while($stmt->fetch()) {
$i++;
$name='t'.$i;
$$name = array();
foreach ($row as $b=>$elem) {
$atul[$b]=$row[$b];
}
$$name=$atul;
}
return array($t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10);
$stmt->close();
}
}
now their are only 5 rows of data so their is no point returning $t6,$t7,$t8,$t9,$t10
and i want to fix it ,and i am calling the function using
$extract=extracting_comments($table, $fields,$condition,$order,$limit);
please help...thanks

Just build the array in your for loop:
function abc($i=3) {
$array = array();
for ($a=1; $a<=$i; $a++) {
$array[] = "ae".$a;
}
return $array;
}
After you edited your question an revealed us your actual problem, see here my proposal:
function extracting_comments($table, $fields, $condition, $order, $limit) {
$retVal = array();
$query = "SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if ($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
call_user_func_array(array($stmt, 'bind_result'), $row);
while ($stmt->fetch()) {
$retVal[] = $row;
}
$stmt->close();
return $retVal;
}
}

I believe this will help you. You have very complicated code with a lot of side effects and bug, you'd better to consider to redisgn it. Also putting statements after return will no have any effect, since it wouldn't be invoked.
function extracting_comments($table, $fields,$condition,$order,$limit){
$query="SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
$params = array();
foreach($row as $k=>$v) {
$params[] = &$row[$k];
echo $params[0];
}
call_user_func_array(array($stmt,'bind_result'),$params);
$i=0;
$result = array();
while($stmt->fetch()) {
$i++;
foreach ($row as $b=>$elem) {
$atul[$b]=$row[$b];
}
$result[]=$atul;
}
$stmt->close();
return $result;
}
}

It'd be cleaner to build the array as you go along, then you wouldn't need the temporary variables:
function abc($i="3") {
$myArray = array();
for($a=1;$a<=$i;$a++) {
$myArray[] = "ae" . $a; // add new values to the end of the array
}
return $myArray;
}
If you want to check if the variables exist (and are not null), use isset().

Related

How to convert Amount from string to float in sql array?

I have problem connected with function returning array from sql query. The problem is that I want to return category as string and amount as float. I think the best solution is to set in while loop to write that i want category as string and amount as float. But I don't know which function can I use to make this ?
I was thinking to write something like this in while loop
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$data[] = [(string)$row['Category'],(float)$row['Amount']];
}
But there is no result, that I expected.
public static function getPieChartIncomes()
{
if (empty(Income::$this->errors)) {
$sql = "SELECT income_category_assigned_to_user_id as Category, SUM(amount) as Amount FROM incomes WHERE user_id = :userId GROUP BY income_category_assigned_to_user_id ORDER BY SUM(amount) DESC ";
$db = static::getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':userId', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$data=array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$data[] = $row;
}
return $data;
}
return false;
}
public static function convertDataToChartForm($data)
{
$newData = array();
$firstLine = true;
foreach ($data as $dataRow)
{
if ($firstLine)
{
$newData[] = array_keys($dataRow);
$firstLine = false;
}
$newData[] = array_values($dataRow);
}
return $newData;
}
Finally I wanted to achieve Array for google charts like this one:
$chartIncomesArray = Income::convertDataToChartForm($incomesArray);
json_encode($chartIncomesArray) =
['Category']['Amount']
['wynagrodzenie'][12.00]
['odsetki'][50.00]
etc.
Can anybody help me with this ?
I solved my problem, deleting convertDataToChartForm($data) and changing getPieChartIncomes function to this:
public static function getPieChartIncomes()
{
if (empty(Income::$this->errors)) {
$sql = "SELECT income_category_assigned_to_user_id as Category, SUM(amount) as Amount FROM incomes WHERE user_id = :userId GROUP BY income_category_assigned_to_user_id ORDER BY SUM(amount) DESC ";
$db = static::getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':userId', $_SESSION['user_id'], PDO::PARAM_INT);
$i = 1;
$stmt->execute();
$tablica = array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$firstLine = true;
if ($firstLine)
{
$tablica[0] = array_keys($row);
$firstLine = false;
}
$category = $row['Category'];
$amount = $row['Amount'];
$tablica[$i]=array(strval($category),floatval($amount));
$i++;
}
return $tablica;
}
Thanks to while loop like now i can get table, where array keys are strings and another rows are : category as string and amount as int like this
['Category']['Amount']
['wynagrodzenie'][12.00]
['odsetki'][50.00]

Pass table variable to SELECT function

I have a getData() function, and a database with two tables: employers and members.
I would like to pass a variable containing the table name, so inside an "if" I could execute the appropriate SELECT statement. My problem I believe that after the "if" the $stmt->bind_param(); doesn't know which $stmt to bind the take.
Any ideas on how I could achieve this?
Thanks
public function getData($table)
{
if ($table == "employers")
{
$stmt = $this->link->prepare("SELECT * FROM employers ");
}
else
{
$stmt = $this->link->prepare("SELECT * FROM members ");
}
$stmt->bind_param();
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
No, since you aren't binding anything, that ->bind_param method is superfluous. Just take that off.
public function getData($table)
{
$dataArray = array();
$t = ($table === 'employers') ? 'employers' : 'members';
$query = "SELECT * FROM $t";
$stmt = $this->link->prepare($query);
if($stmt->execute()) {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
Sample Usage:
$data = $aministrator_query->getData('members');
$tbody = '';
foreach($data as $row) {
$tbody .= "<tr><td>{$row['user_id']}</td><td>{$row['user_password']}</td><td>{$row['user_first_name']}</td><td>{$row['user_last_name']}</td></tr>";
}
$table = sprintf('<table><thead><tr><th>ID</th><th>Password</th><th>First Name</th><th>Last Name</th></tr></thead><tbody>%s</tbody></table>', $tbody);
echo $table;

PHP MySQLi function get user data can't work

i am using This code for showing user data record but this code is not work on my side
I want to echo out specific user data. I created a function where I insert multiple arguments (each argument represents a column in the database) and then echo whichever column I want with a simple line of code.
Index.php
include('function.php');
$conn = new MySQLi(localhost, root, password, database);
$user_id = $_SESSION['login_user']; // like 1
$user = user_data($conn, $user_id, 'login', 'pass', 'nikename', 'email');
if(empty($user)){
echo 'error'; // always showing this error
}else{
echo $user['nickename'];
}
Always Showing echo 'error';
function user_data($conn, $user_id){
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
unset($func_get_args[1]);
$valid = array('login', 'pass', 'nikename', 'email');
$fields = array();
foreach($func_get_args as $arg) {
if(in_array($arg, $valid)) $fields[] = $arg;
}
$fields = '`' . implode ('`, `', $fields) . '`';
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('si', $fields, $user_id);
$stmt->execute();
//here I am trying to convert the result into an array
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
return $results;
$stmt->close();
}
}
}
Seeing and analyzing your code several times, I think the below will solve your issue.
Add this before your while/fetch loop
$row = array();
stmt_bind_assoc($stmt, $row);
so your code will look like this
$row = array();
stmt_bind_assoc($stmt, $row);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
Also make sure you read the full documentation of bind_param on php.net here
Thanks and Best Regards
I guess, instead of
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('si', $fields, $user_id);
you should go with
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('i', $fields, $user_id);
Bind parameters. Types: s = string, i = integer, d = double, b = blob
As far as you have one argument with type INT you need to pass 'i' as a first parameters.
Try debugging over line by line in that function where you will get exact flaw by var_dump().

PHP MySQLi Prepared Statement: Fetch Not Returning Results for Joins

I forget where I copied it from (I think a user posted it on php.net) but this function for fetching results of prepared and normal MySQLi statements is not returning any results when used with statements that contain a simple INNER JOIN, at least the one I tried:
function fetch($result){
$array = array();
if($result instanceof mysqli_stmt){
$result->store_result();
$variables = array();
$data = array();
$meta = $result->result_metadata();
while($field = $meta->fetch_field()){
$variables[] = &$data[$field->name];
}
call_user_func_array(array($result, 'bind_result'), $variables);
$i=0;
while($result->fetch()){
$array[$i] = array();
foreach($data as $k=>$v)
$array[$i][$k] = $v;
$i++;
}
}elseif($result instanceof mysqli_result){
while($row = $result->fetch_assoc())
$array[] = $row;
}
return $array;
}
I've been trying to use it like so (all these functions are methods of the class $database):
function query($str, $values){
if($stmt=$this->sql->prepare($str)){
$types=$this->castArrayAsString($values); //returns a string of $values's types for bind_params
array_unshift($values, $types);
call_user_func_array(array(&$stmt, 'bind_param'), $this->makeValuesReferenced($values));
$stmt->execute();
$result=$this->fetch($stmt); //the function I'm having problems with
if(empty($result)){
$return=true;
}else{
$return=$result;
}
$stmt->close();
}else{
echo $this->sql->error;
$return=false;
}
return $return;
}
This returns nothing:
$list=$database->query("SELECT a.field1, b.field2 FROM table1 AS a INNER JOIN table2 AS b ON a.id_table2=b.id WHERE a.someid=?", array($someid));
This works fine:
$list=$database->query("SELECT field1, field2 FROM table1 WHERE someid=?", array($someid));
If I print out the meta data from fetching the result, it shows that fields are selected, etc, but still gives no final results in the fetch() func.
Any help is appreciated,
Thanks
EDIT HERE IS THE WHOLE CLASS
<?php
class database{
var $HOST="xx.xx.xx.xxx";
var $USER="xxxxxxxxxxx";
var $PASS='xxxxxxxxxx';
var $DATABASE="my_database";
var $sql;
function database(){
$this->sql=new mysqli($this->HOST, $this->USER, $this->PASS, $this->DATABASE);
if($this->sql->connect_errno){
echo "ERROR - No MySQL connection: ".$mysqli->connect_error;
exit;
}
}
function query($str, $values){
if($stmt=$this->sql->prepare($str)){
$types=$this->castArrayAsString($values);
array_unshift($values, $types);
call_user_func_array(array(&$stmt, 'bind_param'), $this->makeValuesReferenced($values));
$stmt->execute();
$result=$this->fetch($stmt);
if(empty($result)){
$return=true;
}else{
$return=$result;
}
$stmt->close();
}else{
echo $this->sql->error;
$return=false;
}
return $return;
}
function fetch($result){
$array = array();
if($result instanceof mysqli_stmt){
$result->store_result();
$variables = array();
$data = array();
$meta = $result->result_metadata();
while($field = $meta->fetch_field()){
$variables[] = &$data[$field->name];
}
call_user_func_array(array($result, 'bind_result'), $variables);
$i=0;
while($result->fetch()){
$array[$i] = array();
foreach($data as $k=>$v)
$array[$i][$k] = $v;
$i++;
}
}elseif($result instanceof mysqli_result){
while($row = $result->fetch_assoc())
$array[] = $row;
}
return $array;
}
function close(){
$this->sql->close();
}
function castArrayAsString($array){
$types="";
foreach($array as $key => $value) {
if(is_numeric($value)){
if(is_float($value)){
$types.="d";
}else{
$types.="i";
}
}else{
$types.="s";
}
}
return $types;
}
function makeValuesReferenced($arr){
$refs=array();
foreach($arr as $key => $value){
$refs[$key] = &$arr[$key];
}
return $refs;
}
}
$database=new database;
?>
The query that returns 0 result set is doing an 'inner-join', which means that the source table and the target table must share the same value for the columns being linked against in the query (in this case a.id_table2 and b.id). Chances are you don't have any matching values so you are getting a 0 result set. Try a left outer join.
Try the following and see if your results are returned:
"SELECT a.field1, b.field2 FROM table1 AS a INNER JOIN table2 AS b ON a.id_table2=b.id WHERE a.someid = :someId"
$dbo = new Database();
$stmt = $dbo->sql->prepare($sql);
$stmt->bindValue(':someId', $someId, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
var_dump($row);
}

How to get array of row objects from my result in mysqli prepared query

I would like to return all the results from my prepared query (mysqli) as objects in an array but i cant find a fetchall method or something similar. How do i go about this?
public function getImageResults ($search_term)
{
if (empty($search_term))
return false;
$image_query = $this->db_connection->stmt_init();
$image_query_sql =
"
SELECT
Images.url as url
FROM
Images, ImageSearch, ImageSearchResults
WHERE
ImageSearch.search_string = ? AND
ImageSearchResults.search_id = ImageSearch.id AND
ImageSearchResults.image_id = Images.id AND
Images.deleted = 0 AND
ImageSearch.deleted = 0 AND
ImageSearchResults.deleted = 0
";
if ($image_query->prepare($image_query_sql))
{
$image_query->bind_param('s', $search_term);
$image_query->execute();
$image_query->store_result();
$image_query->bind_result($url);
return //need to return the entire result set here... any ideas?
}
return false;
}
I found this code on the net which kinda works but i get this error when i use it
Notice: Use of undefined constant
mysqli_stmt_bind_result - assumed
'mysqli_stmt_bind_result'
private function getresult ($stmt)
{
$result = array();
$metadata = $stmt->result_metadata();
$fields = $metadata->fetch_fields();
for (;;)
{
$pointers = array();
$row = new stdClass();
$pointers[] = $stmt;
foreach ($fields as $field)
{
$fieldname = $field->name;
$pointers[] = &$row->$fieldname;
}
call_user_func_array(mysqli_stmt_bind_result, $pointers);
if (!$stmt->fetch())
break;
$result[] = $row;
}
$metadata->free();
return $result;
}
The mysqli_stmt_bind_result on this line:
call_user_func_array(mysqli_stmt_bind_result, $pointers);
should be quoted:
call_user_func_array('mysqli_stmt_bind_result', $pointers);
You could also use PDO, an untested example but it should work:
public function getImageResults ($search_term)
{
$sql =
"
SELECT
Images.url as url
FROM
Images, ImageSearch, ImageSearchResults
WHERE
ImageSearch.search_string = ? AND
ImageSearchResults.search_id = ImageSearch.id AND
ImageSearchResults.image_id = Images.id AND
Images.deleted = 0 AND
ImageSearch.deleted = 0 AND
ImageSearchResults.deleted = 0
";
$pdo = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'username', 'password');
$sth = $pdo->prepare($sql);
$sth->execute(array($search_term));
$result = $sth->fetchAll(PDO::FETCH_CLASS, "ArrayObject");
//var_dump($result);//debug
return $result;
}
Hm, you could try something like this, if I remember correctly:
call_user_func_array(array($stmt, 'bind_result'), $pointers);

Categories