In the example below I am taking an array of the ID's only to turn it into a while and then back into an array only to explode it on the comma on the page. Surely there must be an easier way of doing this.
I am after an array of the $row['ID']s
function get_other_elector_phone($telephone,$current,$criteria){
$the_others = mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria"); $results = '';
while($row = mysql_fetch_array($the_others)) {
$results .= $row['ID'].','; } return $results;
}
$others = get_other_elector_phone(g('electors',$elector,'telephone'),$elector,$criteria);
if($others){ $others = explode(',',$others);
just as #daverandom said, just rebuild an array, this is the syntax :
function get_other_elector_phone($telephone,$current,$criteria){
$the_others=mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria");
$results = array();
$i=0;
while($row = mysql_fetch_array($the_others)) {
$results [$i]= $row['ID'];
$i++;
}
//results returned outside loop
return $results;
}
$others = get_other_elector_phone(g('electors',$elector,'telephone'),$elector,$criteria);
The $others will return an array.
instead of
function get_other_elector_phone($telephone,$current,$criteria){
$the_others = mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria"); $results = '';
while($row = mysql_fetch_array($the_others)) {
$results .= $row['ID'].','; } return $results;
}
}
just return the result of mysql_fetch_array()
function get_other_elector_phone($telephone,$current,$criteria){
$the_others = mysql_query("SELECT * FROM electors WHERE telephone = '$telephone' $criteria"); $results = '';
return mysql_fetch_array($the_others);
}
then there is no need to explode the output of the function.
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;
}
I try to insert result of query into some file.
The file is created but it contain nothing.
I check the query result and its working, i receive a result data.
here is my controller code :
$members_nik = array();
$members_nik = select_config_by('member', 'member_nik', 'WHERE 1=1');
file_put_contents("data.txt", implode(', ', $members_nik));
here is my function code :
function select_config_by($table, $obj, $where){
$query = mysql_query("SELECT $obj as result FROM $table $where");
$row = mysql_fetch_array($query);
$result = $row['result'];
return $result;}
You are returing a string from the select_config_by function but then trying to implode it as if it were an array.
Now assuming you want to return all the results and save them in your data.txt, change the function to this:
function select_config_by($table, $obj, $where)
{
$result = mysql_query("SELECT $obj as result FROM $table $where");
$temp = array();
while ($row = mysql_fetch_array($result))
{
$temp[] = $row['result'];
}
return $temp;
}
Currently I'm working on a project, which using the depth first search to retrieve value, but I'm only able to echo the value, but I don't know how to store the value into the variable.
Here is my code
function calculate_ttl_member_agent ($conn, $id) {
$id_val = $level = "";
$search_dl_sql = "select * from table where foreign_ID = ".$id;
$search_dl_exe = mysqli_query($conn, $search_dl_sql);
while($result = mysqli_fetch_assoc($search_dl_exe)) {
$level = $result['level'];
$id_val = $result['ID'];
echo ",'".$level."'";
calculate_ttl_member_agent ($conn, $id_val);
}
}
I have been trying the use return, but it only give the first level value..
Create an array and add values to it.
function calculate_ttl_member_agent ($conn, $id) {
$id_val = $level = "";
$search_dl_sql = "select * from table where foreign_ID = ".$id;
$search_dl_exe = mysqli_query($conn, $search_dl_sql);
// define an empty array
$arr = [];
while($result = mysqli_fetch_assoc($search_dl_exe)){
$level = $result['level'];
$id_val = $result['ID'];
echo ",'".$level."'";
calculate_ttl_member_agent ($conn, $id_val);
array_push( $arr, [$level, $id_val, 'add anything else needed']);
return $arr;
}}
Store values in an array as commented by Alexanderp and use after
// inside while
$level = $result['level'];
$id_val = $result['ID'];
$level[]= $level;
or
$arr['level'][] = $result['level'];
$arr['id_val'][] = $result['ID'];
I am working on an MLM application in which i need to show all users as a tree. For this is implemented parent child relationship among the users. my table structure is here :-
I had retrieve the id's of users in a multidimensional array as per the relation. Here is array:-
For this i used this code :-
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('testapp', $con);
function create_tree( $parent_id = 0 )
{
$result_array = array();
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id']);
}
}
}
return $result_array;
}
$tree = create_tree();
print_r($tree);
Now, i need to show the data in a tree structure like :-
Any hint will be helpful. I am very near to complete this...
Yes, you are so near..!!
Try below it will be work for you..
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('testapp', $con);
function create_tree( $parent_id = 0 ,$result_array = array())
{
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id'],$result_array);
}
}
}
return $result_array;
}
$tree = create_tree();
print_r($tree);
?>
If this will not work for you than let me know..!!
Thanks..
try that, it should give you the structure;
function create_tree( $parent_id = 0 , $result_array = array() )
{
//$result_array = array();
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id'], $result_array[$row['user_id']]);
}
}
}
return $result_array;
}
edit; forgot the remove result_array in function
I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function